在我的代码中的某个地方,我有一个本地 std::unique_ptr<T>
。我需要用指向的对象做一些事情,我为此使用了一个函数:
std::unique_ptr<T> some_function( std::unique_ptr<T> &t )
{
// do stuff
return t;
}
我这样调用该函数:
std::unique_ptr<T> some_T_ptr( new T(/*args*/) );
vector_of_finalized_Ts.push_back( std::move(some_function(std::move(some_T_ptr))));
现在我想知道,是否有更好的方法来获得必要的功能?看来这两个举动相当多余,而且有潜在的危险。我确实有错误处理代码,但我没有在此处显示,但这不是重点。
最佳答案
一切都与所有权有关。您是否希望 some_function
获得指针的所有权?如果没有,您只需将原始指针传递给 some_function
即可。如果您希望 some_function
获取所有权(并返回所有权),那么它应该按值获取 unique_ptr
。否则,返回语句(应该是 std::move(t)
)将从未知来源的引用中 move 。
std::unique_ptr<T> some_function( std::unique_ptr<T> t )
{
// I own t here and will delete it if an exception happens
// do stuff
// I'm transferring ownership back to the caller
// (who may or may not accept ownership)
return std::move(t);
}
vector_of_finalized_Ts.push_back( some_function(std::move(some_T_ptr)));
或者:
void some_function( T* t )
{
// I don't own t and won't delete it if an exception happens
// do stuff
}
some_function(some_T_ptr.get());
vector_of_finalized_Ts.push_back( std::move(some_T_ptr));
两种设计都可以。它仅取决于什么代码应该拥有该指针(特别是在某个时刻抛出异常时)。
关于c++11 - 修改 std::unique_ptr<T> 指向的对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5923266/