unique_ptr and lambdas

C++11 introduced by default several of the smart pointer types, e.g., unique pointers, shared pointers, etc. One of the features it was lacking was the ability to pass in a unique_ptr into a lambda expression. For example, the following wouldn’t work:

void aFunction(std::unique_ptr<MyClass> aPtr) {
  // do something with aPtr
}

int main() {
    // declare a unique_ptr of MyClass
    std::unique_ptr<MyClass> aPtr(new MyClass());

    // Would like to transfer ownership of aPtr to the lambda expression 
    // to be executed in a separate thread. But it errors out during
    // compile
    std::thread aThread([aPtr] { aFunction(std::move(aPtr)); });   
    aThread.join();

    return 0;
}

This is because lambda’s capture list requires a copyable object to be passed in. However, a unique_ptr is not a copyable object. The compilation error tells you that explicitly:

/usr/include/c++/4.9/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;

In C++14, the standard is updated to allow via Lambda generalized capture. However, I have not be able to get it working for the above example on XCode 8.0.

Leave a Reply

Your email address will not be published. Required fields are marked *