c++11 - 修改 std::unique_ptr<T> 指向的对象的函数

标签 c++11 move unique-ptr

在我的代码中的某个地方,我有一个本地 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/

相关文章:

C++ `this` 指针

c++ - 了解 C++11 的 Lambda 中的 move 捕获

macos - 在 Mac 终端应用程序中 move 选项卡的快捷方式?

C++ unique_ptr 导致应用程序崩溃

c++ - std::unique_ptr 是 RAII 的应用吗?

C++11:我应该使用 valarray 还是向量进行数值计算

c++ - 需要对 C++11 标准中的 8.5.p7 进行一些说明

c++ - 转换正确性 - ID2D1Brush 到 ID2D1SolidColorBrush (DirectX)

c++ - 右值引用和 SFINAE

c++ - 处理容器中的 unique_ptr