c++ - 为什么此时无法引用智能指针auto_ptr?

标签 c++ pointers

#include <memory>
#include <iostream>

using namespace std;
class MyClass
{
public:
    int i;
    MyClass(int s) {
        i=s;
    }
    ~MyClass() {
        cout<<"This class has been destroied.  "<<i<<endl;
    }
    void myFunc() {
        cout<<"myFunc() done.  "<<i<<endl;
    }
};

int main()
{
    auto_ptr<MyClass> ptr1(new MyClass(1));
    auto_ptr<MyClass>ptr2(new MyClass(2));
    ptr1->myFunc();
    ptr2->myFunc();
    cout<<"test 1 done\n"<<endl;

    ptr2 = ptr1;
    ptr2->myFunc();
    //ptr1->myFunc();
    cout<<"test 2 done\n"<<endl;
}
/*
$ ./a.out 
myFunc() done.  1
myFunc() done.  2
test 1 done

This class has been destroied.  2
myFunc() done.  1
test 2 done
 * */

如果上面的ptr1->myFunc();没有被注释掉,那么结果如下。但我无法理解。我认为那个时候ptr1没有被销毁...... 谁能帮忙解释一下?

$ ./a.out 
myFunc() done.  1
myFunc() done.  2
test 1 done

This class has been destroied.  2
myFunc() done.  1
Segmentation fault (core dumped)

最佳答案

旧的 auto_ptr 在复制或分配时有非常奇怪的行为。它具有传输 语义而不是复制语义。这意味着当你说 ptr2 = ptr1; 时,ptr1 实际上已经改变了:它不再指向任何东西。 (而ptr2原来指向的东西当然已经被删除了。)

因此,在从 分配给它之后,您不能使用 ptr1(直到您再次将 分配给 或重置它)。


尽管这样的智能指针是一件非常令人向往的事情,但这种行为如此尴尬的事实表明该语言中缺少某些东西。正确的解决方案需要右值引用,而试图解决与 auto_ptr 相同问题的新 unique_ptr 表现得更明智:您根本无法复制或复制分配它,但您可以移动它——这是该语言的新部分:

unique_ptr<MyClass> ptr1(new MyClass), ptr2(new MyClass);

ptr2 = std::move(ptr1);  // now it's clear that ptr1 is no longer usable

assert(!ptr1);

关于c++ - 为什么此时无法引用智能指针auto_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14110587/

相关文章:

c - 有没有更有效的方法在不使用数组的情况下使用指针对整数进行排序?

c++ - 链表 : Segmentation fault

c++ - VC++ 运行时错误 : Debug Assertation Failed

C++ unique_ptr 和数组

c - 为什么我得到 "dereferencing pointer to incomplete type"?

C++:如何在声明它的模板类主体之外定义枚举类?

c++ - C++对象复制

c++ - 是否可以识别与某些头文件对应的库?

c++ - 对象组合促进代码重用。 (T/F,为什么)

python - 如何重组 R 中由 8 个重复行和 24 列组成的数据?