我试图理解在下面使用 lambda 表达式的示例中通过引用或通过值捕获变量的含义。
/** Encapsulates the private implementation details of Thread. */
struct Thread::Impl
{
public:
Impl() : m_queue(), m_thread()
{
}
private:
Impl(const Impl&);
const Impl& operator=(const Impl&);
void run()
{
// do some work
}
std::unique_ptr<std::thread> m_thread;
friend class Thread;
};
Thread::Thread() : m_impl(new Impl())
{
// start the thread
// ************************************
// '=' or '&' in the the capture block?
// ************************************
m_impl->m_thread = std::unique_ptr<std::thread>(new std::thread( [&]{ m_impl->run(); } ));
}
无论我在捕获 block 中使用 &
还是 =
,上面的代码都可以正常工作。那么我应该使用哪个?
如果我使用[&]
,m_impl
是通过引用捕获的,对吧?
如果我使用[=]
m_impl
是按值捕获的,对吗?但我不明白为什么它会编译。它在复制什么? Impl 的复制器已禁用。
最佳答案
If I use
[&]
,m_impl
is captured by reference, right? If I use[=]
m_impl
is captured by value, right?
这些都不是真的。 m_impl
根本没有被捕获。在这两种情况下,都会捕获 this
。但由于thread
是您捕获的this
指针对象的成员变量,因此this(哈!)是安全的。
使用您喜欢的任何一个。或者[this]
,如果你想更明确的话。
关于c++11 - ' &' or ' =' 在 lambda 捕获表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42115613/