还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

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

来源:清泛原创     2020-10-15 11:14:39    人气:     我有话说( 0 人参与)

编译报错日志如下: usr include c++ 4 7 bits stl_construct h:77:7: error: use of deleted function & 39;std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_p

编译报错日志如下:

/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

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: