c++11 - ' &' or ' =' 在 lambda 捕获表达式中?

标签 c++11 lambda stdthread

我试图理解在下面使用 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/

相关文章:

c++ - 模板化构造函数与模板化复制构造函数

c++ - std::bind 于 std::array 的运算符[]

Java "target type of lambda conversion must be an interface"

c++ - 并行填充 vector ,顺序不重要

c++ - 有没有办法禁用非常规类型的自动声明?

C++ lambda回调触发事件

c# - 这两种说法有什么区别?

C++11 condition_variable 同步问题

c++ - 在 C++11 中设置 std::thread 优先级的可移植方法

c++ - 分配器感知容器和 propagate_on_container_swap