c++ primer plus 第16章string 类和标准模板库,16.2.1 使用智能指针
c++ primer plus 第16章string 类和标准模板库,16.2.1 使用智能指针
16.2.3 unique ptr为何优于 auto ptr
请看下面的语句:
auto ptr<string>pl(new string("auto");//#1
auto ptr<string>p2;//#2
p2 = p1;//#3
在语句#3中,p2接管string 对象的所有权后,p1的所有权将被剥夺。前面说过,这是件好事,可防止p1和p2的析构函数试图删除同一个对象;但如果程序随后试图使用p1,这将是件坏事,因为p1不再指向有效的数据。
下面来看使用unique ptr的情况:
unique_ptr<string>p3(new string("auto");