Answered by:
std::unique_ptr with lambda

Question
-
I am trying to access a unique_ptr in a lambda but I get the following compile errors:
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
Code looks like this:
#include "stdafx.h" #include <memory> #include <vector> #include <algorithm> class Message { public: Message() {} }; int main(int argc, char* argv[]) { std::vector<std::unique_ptr<Message>>messages; for (int i = 0; i < 1000; i++) { std::unique_ptr<Message> testMess; messages.push_back(std::move(testMess)); } std::for_each(messages.begin(), messages.end(), [](std::unique_ptr<Message> testMess) { // do something stupid }); return 0; }
Wednesday, December 14, 2011 5:13 PM
Answers
-
The way you wrote the lambda will cause a copy of the unique_ptr to be made, that's not possible, it's supposed to be unique after all. Use a reference instead:
std::for_each(messages.begin(), messages.end(),
[](const std::unique_ptr<Message>& testMess) {
// do something stupid
});
- Marked as answer by Anonymous7520 Wednesday, December 14, 2011 5:25 PM
Wednesday, December 14, 2011 5:19 PM
All replies
-
The way you wrote the lambda will cause a copy of the unique_ptr to be made, that's not possible, it's supposed to be unique after all. Use a reference instead:
std::for_each(messages.begin(), messages.end(),
[](const std::unique_ptr<Message>& testMess) {
// do something stupid
});
- Marked as answer by Anonymous7520 Wednesday, December 14, 2011 5:25 PM
Wednesday, December 14, 2011 5:19 PM -
The way you wrote the lambda will cause a copy of the unique_ptr to be made, that's not possible, it's supposed to be unique after all. Use a reference instead:
std::for_each(messages.begin(), messages.end(),
[](const std::unique_ptr<Message>& testMess) {
// do something stupid
});
Thanks a lot.Wednesday, December 14, 2011 5:25 PM -
On 12/14/2011 12:13 PM, Anonymous7520 wrote:
I am trying to access a unique_ptr in a lambda but I get the following compile errors:
error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
std::for_each(messages.begin(), messages.end(),
[](std::unique_ptr<Message> testMess) {You are passing unique_ptr by value. That would require copying it, but it can't be copied.
Igor Tandetnik
Wednesday, December 14, 2011 5:26 PM