【发布时间】:2018-03-05 17:39:21
【问题描述】:
我想知道是否有任何正当理由在 C++ 中通过引用返回唯一指针,即std::unique_ptr<T>&?
我以前从未真正见过这种技巧,但我得到的新项目似乎大量使用了这种模式。乍一看,它只是有效地打破/规避了“唯一所有权”合同,从而无法在编译时捕获错误。考虑以下示例:
class TmContainer {
public:
TmContainer() {
// Create some sort of complex object on heap and store unique_ptr to it
m_time = std::unique_ptr<tm>(new tm());
// Store something meaningful in its fields
m_time->tm_year = 42;
}
std::unique_ptr<tm>& time() { return m_time; }
private:
std::unique_ptr<tm> m_time;
};
auto one = new TmContainer();
auto& myTime = one->time();
std::cout << myTime->tm_year; // works, outputs 42
delete one;
std::cout << myTime->tm_year; // obviously fails at runtime, as `one` is deleted
请注意,如果我们只返回std::unique_ptr<tm>(不是引用),它会引发明显的编译时错误,或者会强制使用移动语义:
// Compile-time error
std::unique_ptr<tm> time() { return m_time; }
// Works as expected, but m_time is no longer owned by the container
std::unique_ptr<tm> time() { return std::move(m_time); }
我怀疑一般的经验法则是所有此类情况都需要使用std::shared_ptr。我说的对吗?
【问题讨论】:
-
返回对拥有
std::unique_ptr的引用没有任何意义,恕我直言。 -
您将返回对
unique_ptr的引用,原因与您返回对任何其他类型对象的引用相同。因为你想让调用者能够操纵它。 -
@KillzoneKid:是的。使用
shared_ptr(按值返回),您无法重置原始所有者的指针。 -
我在代码审查中不接受此代码。只需返回存储在其中的原始指针。
-
这闻起来重构变坏了。好像有人的任务是替换代码库中的所有原始指针,并支持
unique_ptr。
标签: c++ shared-ptr unique-ptr