c++ - 自动指针的优点/缺点

标签 c++ smart-pointers

与普通指针相比,使用自动指针(auto_ptr)有哪些优点和缺点?听说有自动释放内存的功能,但为什么不常使用呢?

最佳答案

std::auto_ptr 的主要缺点是它具有所有权转移 语义。这使得无法在 STL 容器中存储 std::auto_ptr,因为当您存储或获取元素时,容器会使用复制构造函数。

此外,我注意到关于 std::auto_ptr 的另一个重要方面是它们不能用于 PIMPL 习语的使用。这是因为,它们需要包装类的析构函数的完整定义。有关更详细的讨论,请参阅 c.l.c++.m 上的 this 线程。

更新:所有权转让

class Test {};
std::auto_ptr<Test> ap_test_1(new Test);
std::auto_ptr<Test> ap_test_2(new Test);

ap_test_2 = ap_test_1;  // here ap_test_1's ownership is transferred i.e. ap_test_2 is the 
                        // new owner and ap_test_1 is NULL.

请参阅 Herb Sutter 网站上的 this 线程,详细了解在 STL 算法使用的 STL 容器中使用时这意味着什么。

关于c++ - 自动指针的优点/缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100486/

相关文章:

c++ - 相同类型布局的变量结构是否与包含该类型数组的结构兼容?

c++ - 在 C++ 中调用函数指针指向的函数的方法

c++ - 封装线程会产生问题

c++ - 将智能指针放入 STL 容器中

c++ - 重载运算符 !=

c++ - 智能指针 : cast between base and derived classes

c++ - 找出单词是否是回文的程序

c++ - OpenCV : homomorphic filter

c++ - 智能指针数组删除器

c++ - 处理 shared_ptr 时未初始化的值