【发布时间】:2014-05-23 10:00:18
【问题描述】:
我正在学习 C++11 功能,作为其中的一部分,我首先进入了 unique_ptr 和 shared_ptr 的世界。
当我开始时,我编写了一些专门使用 unique_ptr 的代码,因此,当我传递我的变量时,我需要使用 std::move 来完成它(或者我是这样理解的)。
经过一番努力,我意识到我确实需要shared_ptr 而不是我正在做的事情。稍后快速查找/替换,我的指针被切换到共享,但我懒惰地只留下了 move() 调用。
令我惊讶的是,它不仅编译了,而且在我的程序中表现得非常好,我得到了我所期待的每一盎司功能......特别是,我能够将 shared_ptr 从 ObjectA 中“移动”到ObjectB,两个对象都可以访问它并且可以操纵它。太棒了。
这对我提出了一个问题……现在我在shared_ptr 上,move() 调用实际上是否在做任何事情?如果是这样,它是什么,它的后果是什么?
代码示例
shared_ptr<Label> lblLevel(new Label());
//levelTest is shared_ptr<Label> declared in the interface of my class, undefined to this point
levelTest = lblLevel;
//Configure my label with some redacted code
//Pass the label off to a container which stores the shared_ptr in an std::list
//That std::list is iterated through in the render phase, rendering text to screen
this->guiView.AddSubview(move(lblLevel));
此时,我可以对 levelTest 进行重要更改,例如更改文本,这些更改会反映在屏幕上。
这对我来说似乎levelTest 和列表中的shared_ptr 都是同一个指针,而move() 确实没有做太多事情。这是我的业余解释。寻找洞察力。在 Windows 上使用 MinGW。
【问题讨论】:
标签: c++ c++11 shared-ptr move-semantics unique-ptr