与普通指针相比,使用自动指针(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/