如何从lambda中分配unique_ptr值

  • 本文关键字:unique ptr 分配 lambda c++
  • 更新时间 :
  • 英文 :


我有一个情况,我需要从lambda函数中分配一个唯一的ptr值。

std::unique_ptr<SomeType> unique_ptr_obj;
// Lambda below has fixed return type.
bool var = ()[unique_ptr_obj=std::move(unique_ptr_obj)]-> bool {
unique_ptr_obj = GetUniqueObject();
return true 
} ();

// Should be able to use unique_ptr_obj
UseUniqueObject(unique_ptr_obj.get());

然而,正如预期的那样,unique_ptr_obj是nullptr,因为它被移动到lambda中。是否有一种方法可以从lambda内填充unique_ptr_obj并能够在以后重用它?

有什么建议吗?我应该把unique_ptr_obj转换成shared_ptr吗?

您应该更改lambda的声明以通过引用捕获unique_ptr_obj:

bool var = [&unique_ptr_obj]() -> bool {
// Whatever the next line does, now it changes that variable by reference.
// Otherwise you were changing a local copy.
unique_ptr_obj = GetUniqueObject();
return true;
} ();

你不想分享所有权。或者你可能会这样做,但它不会帮助lambda将某些东西分配给unique_ptr_obj,因此使用shared_ptr不是解决方案。

您也不想从unique_ptr_obj移动。粗略地说,离开某物意味着让它处于空状态。

如果你想让一个函数修改它的实参,那么你可以通过引用传递。如果你想让lambda在外部作用域中修改一些东西,你可以让它通过引用来捕获它。

intunique_ptr都是一样的:

int x = 0;
bool value = [&x]() { x = 42; return true; } ();
//   ^^ capture x by reference
assert(x == 42);

最新更新