如何:创建和使用unique_ptr实例

A unique_ptr不会共享它的指针。无法将它复制到另一个unique_ptr,(除非它是可修改 rvalue) 通过值传递给函数,或需要对其进行复制的任何标准模板库 (STL) 算法中使用。A unique_ptr只能移动。这意味着内存资源的所有权将转移到新的unique_ptr和原始unique_ptr不再拥有它。我们建议您将一个对象限制为一个所有者,因为拥有多个程序逻辑增加复杂性。因此,当您需要为普通的 C++ 对象的智能指针,使用unique_ptr

下图说明了两个转让所有权unique_ptr实例。

移动 unique_ptr 的所有权

unique_ptr在中定义<memory> STL 中的标头。它是完全有效与原始指针,可以使用 STL 容器中。添加unique_ptr是有效的实例的 STL 容器因为移动构造函数的unique_ptr不需要复制操作。

示例

下面的示例演示如何创建unique_ptr实例,并将它们传递函数之间。

unique_ptr<Song> SongFactory(std::wstring artist, std::wstring title)
{
    // Implicit move operation into the variable that stores the result.
    return unique_ptr<Song>(new Song(artist, title));
}

void MakeSongs()
{
    // Create a new unique_ptr with a new object.
    unique_ptr<Song> pSong = unique_ptr<Song>(new Song(L"Mr. Children", L"Namonaki Uta"));

    // Use the unique_ptr
    vector<wstring> titles;
    titles.push_back(pSong->title);

    // Move raw pointer from one unique_ptr to another.
    unique_ptr<Song> pSong2 = std::move(pSong);

    // Obtain unique_ptr from function that returns rvalue reference.
    auto pSong3 = SongFactory(L"Michael Jackson", L"Beat It");
}

这些示例演示了此基本特性的unique_ptr: 它可以移动,但不是会被复制。"移动"将转移到新的所有权unique_ptr ,并重置旧unique_ptr

下面的示例演示如何创建unique_ptr实例,并使用它们在向量中。

void SongVector()
{
    vector<unique_ptr<Song>> v;

    // Create a few new unique_ptr<Song> instances
    // and add them to vector using implicit move semantics.
    v.push_back(unique_ptr<Song>(new Song(L"B'z", L"Juice")));
    v.push_back(unique_ptr<Song>(new Song(L"Namie Amuro", L"Funky Town")));
    v.push_back(unique_ptr<Song>(new Song(L"Kome Kome Club", L"Kimi ga Iru Dake de")));
    v.push_back(unique_ptr<Song>(new Song(L"Ayumi Hamasaki", L"Poker Face")));

    // Pass by reference to lambda body. 
    for_each(v.begin(), v.end(), [] (const unique_ptr<Song>& p)
    {
        wcout << L"Artist: " << p->artist << L"Title: " << p->title << endl; 
    });        
}

在for_each循环播放,请注意, unique_ptr由 lambda 表达式中引用传递。如果您尝试通过值传递,因为,编译器将引发错误unique_ptr复制构造函数被禁用。

下面的示例演示如何初始化unique_ptr的类成员。


class MyClass
{
private:
    // MyClass owns the unique_ptr.
    unique_ptr<ClassFactory> factory;
public:

    // Initialize by invoking the unique_ptr move constructor.
    MyClass() : factory ( unique_ptr<ClassFactory>(new ClassFactory()))
    {              

    }

    void MakeClass()
    {
        factory->DoSomething();
    }
};

请参见

概念

智能指针(现代C++)