【发布时间】:2018-06-25 08:53:36
【问题描述】:
我的代码是:
#include <memory>
#include <vector>
struct Core{
Core(int n){} };
int main() {
int base;
std::vector<std::unique_ptr<Core>> cores;
cores.push_back( std::move(std::unique_ptr<Core>(new Core(base))) );
cores[0].swap(std::unique_ptr<Core>(new Core(base)));
return 0;
}
我得到这个错误:
||=== 构建:在测试中发布(编译器:GNU GCC 编译器)===|
函数“int main()”错误:没有匹配函数调用“std::unique_ptr
::swap(std::unique_ptr )” 注意:候选人是:
注意: void std::unique_ptr<_tp>::swap(std::unique_ptr<_tp>&) [with_Tp = Core; _Dp = std::default_delete
] 注意:没有已知的参数 1 从 'std::unique_ptr
' 到 'std::unique_ptr &' 的转换
【问题讨论】:
-
仅供参考:由于访问未初始化的
int base,您的代码具有未定义的行为。此外,执行std::move -
你为什么要换成临时的?
unique_ptr::swap的签名不允许这样做。 -
我想改变我的vector[0]里面的内容,但我不知道怎么做,我想用一个交换,让临时死在作用域的末尾跨度>
-
我的 gcc 版本对用户更友好:
invalid initialization of non-const reference of type ‘std::unique_ptr<Core>&’ from an rvalue of type ‘std::unique_ptr<Core>’
标签: c++ c++11 swap unique-ptr