将 unique_ptr 而不是 * 传递给方法

Passing unique_ptr instead of * to method

我有一个用作 unique_ptr 的 POD,lldb 告诉我它的类型 POD *。 我有一个自由浮动函数,我想将此 POD 的引用传递给,以便我可以填充 public 属性。

如果我向函数添加类型为 POD * 的参数,Clang 编译我的代码没有问题,但如果我尝试传递 unique_ptr<POD> &paramunique_ptr<POD param,它会失败并显示:

Candidate function not viable: no known conversion from ' *' to 'unique_ptr<>'

我想我总是可以传递一个 unique_ptr 在那里我有一个原始指针,反之亦然?

更新,方法签名:

原文:

void connection_fsm(const LogLevel &level, const bytes &barray, unique_ptr<PGOutput> &output) noexcept;

void connection_fsm(const LogLevel &level, const bytes &barray, unique_ptr<Conn> &conn, unique_ptr<PGOutput> &output) noexcept;

void connection_fsm(const LogLevel &level, const bytes &barray, unique_ptr<Conn> conn, unique_ptr<PGOutput> &output) noexcept;

void connection_fsm(const LogLevel &level, const bytes &barray, Conn *conn, unique_ptr<PGOutput> &output) noexcept;

从原始指针到唯一指针的可用转换是这个构造函数:

explicit unique_ptr( pointer p ) noexcept;

由于该构造函数被标记为 explicit,因此不考虑进行 隐式 转换。

这很好,因为如果我们像这样强制转换:

T * raw = get_it_from_somewhere ();
// Assume function takes unique_ptr by value or reference
function(std::unique_ptr<T>{raw});
//              ^^ a temporary
delete raw;

然后临时唯一指针将取得指向对象的所有权,因此在函数调用后删除它!因此,使用上面的代码,您将获得双重删除(当然不能在函数调用后取消引用该指针)。

现在,如果您打算将所有权传递给 function,那很好,但否则您不应使用唯一指针。最好传递一个(如果可能 const )引用或(如果你需要 "nullable" 行为)一个原始指针。

unique_ptr 表示所有权。您要转让所有权吗?如果没有,请不要通过 unique_ptr。请记住 unique_ptr 将在销毁时删除基础对象。出于这个原因,它也是不可复制的(复制一些独特的东西是没有意义的)。

传递原始指针并没有错,只要它们的生命周期超过被调用方法的生命周期。

传递对 unique_ptr 的引用比传递原始指针没有任何价值。最后,它对您不起作用,因为无法将临时(右值)绑定到左值引用。