我的代码是:
#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;
}
我收到这个错误:
|| === Build:Test in Release(编译器:GNU GCC编译器)=== |在函数'int main()'错误:没有匹配函数调用'std :: unique_ptr <Core> :: swap(std :: unique_ptr <Core>)'注意:候选者是:注意:void std :: unique_ptr < _Tp,_Dp> :: swap(std :: unique_ptr <_Tp,_Dp>&)[with_Tp = Core; _Dp = std :: default_delete <Core>]注意:参数1从'std :: unique_ptr <Core>'到'std :: unique_ptr <Core>&'没有已知的转换
3 回答
你不能像这样交换临时对象(
rvalue
):但是临时可以像这样交换命名对象(
lvalue
)或者,您可以直接设置值:
或者(更好)使用std::make_unique
您将对象的构造函数的参数直接传递给
std::make_unique
函数 .如果你必须使用
new
,总会有std::unique_ptr::reset函数:您使用
std::move
太多了 . 在您的情况下,移动会自动发生 . 所以,你可以写或者,使用
std::make_unique
和std::unique_ptr::reset
,但是,如果您将
unique_ptr
(例如)作为局部变量,则必须使用std::move
:这和上面一样有效,但是创建了一个潜在的不必要的局部变量 .
您需要使用左值
std::unique_ptr<Core>
进行交换,不允许使用未命名的临时值 .你能做的是