【发布时间】:2015-07-20 16:53:36
【问题描述】:
我注意到如果我有以下情况:
#include <memory>
using namespace std;
class Foo
{
public:
Foo();
};
class Wobble
{
public:
void SetWibble( unique_ptr<Foo> foo )
{
this->wibble = move( foo );
}
// I like returning a ref as it gives control to
// the user of my framework over recieving a & or a copy
Foo& GetWibble()
{
return *wibble;
}
unique_ptr<Foo> wibble;
};
int _tmain(int argc, _TCHAR* argv[])
{
unique_ptr<Wobble> wobble;
unique_ptr<Foo> foo( new Foo() ); // Look here
foo->something = ...;
foo->something1 = ...;
foo->something2 = ...;
wobble->SetWibble( move( foo ) );
return 0;
}
...当我声明foo 时,我有一个不错的Foo 对象.. 当我将move 的所有权归入wobble 实例时,foo 现在在int _tmain 范围内为空。
我非常喜欢这个,因为我认为它正在删除内存并从 int _tmain 范围中清除指针...在我当前的上下文中,不需要再摆弄它了...与此相反:
// ...
void SetWibble( Foo& foo )
{
this->wibble = foo;
}
// ...
int _tmain(int argc, _TCHAR* argv[])
{
unique_ptr<Wobble> wobble;
Foo foo;
foo.something = ...;
foo.something1 = ...;
foo.something2 = ...;
wobble->SetWibble( foo );
return 0;
}
它仍然在作用域内保留对该变量的引用。
问:
- 我上面说的对吗?
- 我想知道除了我已经指出的那些之外,使用 unique_ptr 和不使用 unique_ptr 是否有任何好处?
【问题讨论】:
-
你可能会觉得这很有趣:herbsutter.com/2013/06/05/…
-
这次我要好好读一下,我想我之前已经被引导到他的...
-
您忘记了在一种情况下您使用的是堆,而在另一种情况下使用的是堆栈,选择取决于应用程序。
-
在你的第二个例子中,我假设
Wobble中的成员变量wibble是一个值,而不是一个引用?即Wobble::SetWibble需要一份副本吗?
标签: c++ unique-ptr