c++11 :unique_ptr

来源:互联网 发布:linux怎么切换用户登录 编辑:程序博客网 时间:2024/06/13 08:48

创建和使用unique_ptr 实例

unique_ptr不共享它的指针。他无法复制到其他的unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库(STL)算法。只能移动unique_ptr,这意味着,内存资源所有权将转移到另一个unique_ptr,并且原始的unique_ptr 不在拥有此资源。建议将对象限制为由一个所有者所有,因为多个所有权会使程序逻辑变的复杂。因此,当需要智能指针用于纯c++对象是,可使用unique_ptr,而构造unique_ptr时,可使用make_unique Helper 函数。
下图演示了两个unique_ptr实例之间的所有权的转换。

unique_ptr 在STL的标头中定义。它与原始指针一样有效,并可用于STL容器,将unique_ptr适量中添加到STL容器很有效,因为通过unique_ptr的移动构造函数,不需要进行复制操作。
以下实例演示如何创建unique_ptr实例并在函数之间传递这些实例

    unique_ptr<Song>SongFactory(const std::wstring& artist,const std::wstring &title)    {        return make_unique<Song>(artist,title);    }    void MakeSongs()    {        auto song=make_unique<Song>("Mr.Children","Namonaki Uta");        vetor<wstring> titles={song->title};        unique_ptr<Song> song2 = std::move(song);        auto song3=SongFactory("Michael Jackson","Beat lt");    }

这些实例说明了unique_ptr的基本特征:可移动不可以复制。“移动”将所有权转移到新的unique_ptr并重置旧unique_ptr.

 void Songvector() {     vector <unique_ptr<Song> > songs;     //create a few new unique_ptr<Song> instances     //ans add them to vector using implicit move semantics.     songs.push_back(make_unique<Song>("xxx","yyy"));     songs.push_back(make_unique<Song>("zzz","kkk"));     for(const auto& song : songs){     cout << song->artist<<song->title<<endl;     }    }

在range for 循环中,注意unique_ptr通过引用来传递。如果你尝试通过此处的值传递,由于删除了unique_ptr 复制构造函数,编译器将引发错误。
以下示例演示如何初始化类成员unique_ptr

class MyClass {private:    unique_ptr<ClassFactory> factory;public:    MyClass():factory(make_unique<ClassFactory>())    {}    void MakeClass()    {        factory->DoSomething();    }    }

可以使用make_unique 创建到数组,但是无法使用make_unique初始化数组元素

  auto p=make_unique<int[]>(5)  for(int i=0;i<5;i++)  {      p[i]=i;  }

参考网址

0 0
原创粉丝点击