I'm new to modern C++ and I think I'm missing some key points about lambda functions and smart pointers that are giving me some trouble when trying to sandbox in the boost libraries.
platform: RHEL7, c++17
I want to pass ownership of a unique_ptr
first to a lambda function and then to a function nested inside of the lambda. Here are a few test cases that I need some help.
class TestClass{
private:
std::string message;
public:
TestClass(std::string message): message(message){}
void printMessage(){std::cout << message << std::endl;}
};
void functionNestedInLambda(std::unique_ptr<TestClass> testClass){
testClass->printMessage();
return;
}
int main(){
auto testClass = std::make_unique<TestClass>("Hello Stack Overflow");
auto lFunction = [&](){functionNestedInLambda(std::move(testClass));};
lFunction();
return 0;
}
This compiles fine, and seems to pass ownership of testClass
to functionNestedInLambda()
. The "pass by reference" within the lambda's capture clause is giving me pause, as I'm not sure how the ownership of testClass
is getting passed to the lambda function. My thought then was try to explicitly transfer ownership to the lambda in the same way as seen in this stack overflow post:
How to capture a unique_ptr into a lambda expression?.
I changed
auto lFunction = [&](){functionNestedInLambda(std::move(testClass));};
to
auto lFunction = [testClass = std::move(testClass)](){functionNestedInLambda(std::move(testClass));};
This creates the following compiler error
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = TestClass; _Dp = std::default_delete<TestClass>]’
139 | auto lFunction = [testClass = std::move(testClass)](){functionNestedInLambda(std::move(testClass));};
It seems to me that this should pass the ownership first to the lambda and then to the nested function, but I'm obviously missing something.
What would be the best way to accomplish this? I want to control object ownership as tightly as possible.
Also, how exactly is the first example compiling? How is ownership handled when passing in the unique pointer as reference to the lambda?