【发布时间】:2019-04-05 06:39:57
【问题描述】:
我正在更新一些使用 auto_ptr 的旧代码以改用 unique_ptr。这主要是一项搜索和替换工作,但我发现在代码返回 unique_ptr 的地方出现编译错误。
这是一个说明问题的示例:
#include <string>
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
struct Foo {
unique_ptr<string> us;
Foo() {
this->us = unique_ptr<string>(new string("hello"));
}
unique_ptr<string> bar() {
return this->us;
}
};
int main(int argc, const char **argv) {
Foo foo;
unique_ptr<string> s = foo.bar();
cout << *s << endl;
}
当我编译它时,我得到了这个:
t1.cpp: In member function ‘std::unique_ptr<std::basic_string<char> > Foo::bar()’:
t1.cpp:17:16: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::basic_string<char>; _Dp = std::default_delete<std::basic_string<char> >]’
return this->us;
^~
In file included from /opt/rh/devtoolset-7/root/usr/include/c++/7/memory:80:0,
from t1.cpp:4:
/opt/rh/devtoolset-7/root/usr/include/c++/7/bits/unique_ptr.h:388:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
如果我改变错误的行来指定这样的移动:
return move(this->us);
然后就可以了。
我发现多个引用表明不需要移动 - 例如来自 chromium 项目的 this SO question 和 these guidelines。
我的问题是:为什么在这种情况下需要明确指定移动?是否与我以某种方式返回实例变量的值有关?
如果这是一个骗局,请提前道歉 - 我确信以前会被问到,但我很难找到找到它的搜索词。
【问题讨论】:
-
如果编译器在不告诉你的情况下将其转移到你身上,它可能会意外地破坏你的类不变量。
-
这不是正确的骗局。 OP 想同时在两个不同的地方使用指针。所以这不是关于返回 unique_ptr,而是使用 shared_ptr !
-
@Christophe:链接的帖子建议使用
shared_ptr
标签: c++ unique-ptr