use of deleted function std::unique_ptr 编译错误剖析,你可能少了一个std::move

清泛原创
编译报错日志如下:
/usr/include/c++/4.7/bits/stl_construct.h:77:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&)
 [with _Tp = MyThread; _Dp = std::default_delete<MyThread>; std::unique_ptr<_Tp, _Dp> = std::unique_ptr<MyThread>]'
In file included from /usr/include/c++/4.7/memory:86:0,
                 from /home/patrickz/git/etsmtl-log710-lab02/include/MyThreadPool.h:6,
                 from ../src/MyThreadPool.cpp:2:
/usr/include/c++/4.7/bits/unique_ptr.h:262:7: error: declared here
make: *** [src/MyThreadPool.o] Error 1
主要代码如下:
class MyThreadPool {
...
private:
    std::vector<std::unique_ptr<MyThread>> threads_;
};
...
MyThreadPool::NewThread() {
    auto thread = make_unique<MyThread>();
    threads_.emplace_back(thread);
}
原因剖析:
根据编译错误提示信息可知,由于unique_ptr拷贝构造函数被delete了,而又发生了unique_ptr的拷贝导致。翻查代码不难发现,由于新建的unique_ptr对象直接赋值给了vector,导致拷贝发生,解决方法很简单,就是加一个std::move即可
//threads_.emplace_back(thread);  --->   
threads_.emplace_back(std::move(thread));

unique_ptr std::move

分享到:
评论加载中,请稍后...
回到顶部