c++ - CppCoreGuidelines R33 为什么通过引用传递 `unique_ptr`?

标签 c++ c++11 cpp-core-guidelines

CppCoreGuidlines rule R.33建议

Take a unique_ptr<widget>& parameter to express that a function reseats the widget.

Reason Using unique_ptr in this way both documents and enforces the function call’s reseating semantics.

Note “reseat” means “making a pointer or a smart pointer refer to a different object.”

我不明白为什么当重新定位意味着“使指针或智能指针引用不同的对象”时我们应该通过引用传递。

当函数的目的是重新定位/更改指针指向的底层对象时,我们不是以这种方式从调用者那里窃取所有权,因此应该传递 unique_ptr按值(value),从而移动它并转移所有权?

有没有一个例子可以解释为什么传递 unique_ptr推荐引用吗?

最佳答案

When the function's purpose is to reseat/change the underlying object the pointer is pointing to, aren't we stealing the ownership from the caller this way

没有。当我们“重新设置”指针时,或者当我们更改指向的对象时,我们都不会获得该指针的所有权,即我们不会转移所有权。

Is there an example that explains why passing a unique_ptr by reference is recommended?

以下是“重新设置”唯一指针的函数示例:

void reseat(std::unique_ptr<widget>& ptr) {
    ptr = std::make_unique<widget>();
}

如果您尝试使用对 const 的引用,那么根本无法编译。如果您尝试使用非引用参数,则参数指针将不会被修改,因此行为不会达到预期的效果。调用者将被迫移动其指针,使其始终为空。

您可以修改示例以使用指向唯一指针的指针,但建议使用引用,因为不可能错误地传递 null。引用包装器也可以工作,但它会变得不必要的复杂。

In case we make it point somewhere else, what happens to the object it pointed before?

如果唯一指针指向 null 以外的其他内容,则将其指向其他位置将导致先前指向的对象被删除。

Aren't we leaking memory in this case?

没有。


请注意,该示例很简单,以便于理解。通常,我不建议编写这样的函数,而是考虑编写一个返回新的唯一指针的函数,并让调用者自己“重新设置”指针。但这取决于细节。

关于c++ - CppCoreGuidelines R33 为什么通过引用传递 `unique_ptr`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69311574/

相关文章:

c++ - 模板化的 Barton 和 Nackman 技巧问题

c++ - std::vector::data() 是否通过 move 保留?

c++ - 我应该尽量使用 const T & 吗?

c++ - 核心 cpp 指南中 f(T*, int) 接口(interface)与 f(span<T>) 接口(interface)的含义

c++ - 为什么我不能构造一个带有大括号括起来的初始化列表的 gsl::span

c++ - QJsonValueRef 与 QJsonValue

c++ - 内容类型 : application/x-www-form-urlencoded in curl

javascript - 获取 json 属性 duktape

c++ - 在 C++0x 中删除虚函数

c++ - 在类和 cpp 核心指南中初始化优先级变量?