为什么智能指针auto_ptr在那个时候不能被引用
Why the smart pointer auto_ptr cannot be referenced at that time?
#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 donen"<<endl;
ptr2 = ptr1;
ptr2->myFunc();
//ptr1->myFunc();
cout<<"test 2 donen"<<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
(直到你再次赋值给或者重置它)。
这种行为是如此的尴尬,尽管这样一个智能指针是一个非常可取的东西,这表明语言中缺少了一些东西。正确的解决方案需要右值引用,新的unique_ptr
,它试图解决与auto_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);
当您执行ptr2 = ptr1;
时,您正在删除当前由ptr2
指向的对象,该对象现在指向以前由ptr1
指向的对象。ptr1
将自己设置为指向null,因为这是auto_ptr
在副本上的语义。然后尝试取消对null的引用,很幸运地出现了崩溃,并发现代码是错误的。
相关文章:
- 将值从另一个数组写入数组,不包括不需要的值 C++
- 使用 cv::不扭曲不失真和居中图像
- C 与C++编译不兼容 - 不命名类型
- 类定义怎么能不占用内存?
- 如何在不指定不必要的模板参数的情况下使用模板类的成员类型
- 一个倒梯形,但如果输入高度对于宽度来说太大,那么它应该报告,不可能("不可能的形状"是什么)
- 模板参数是哪些类型的值?我能(不)用它们做什么
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- glTranslatef拉伸我的球体,我怎么能不拉伸它就平移球体
- 在嵌套CWND衍生的类中,不关注不改变选项卡键
- 为什么 G++ 不为不返回任何内容的模板方法生成警告?
- Cocos2dx动画(不使用不推荐使用的方法)
- 你能不能使用 JNI 在从 java 调用的 c++ 函数中创建一个新的 JVM
- 在使用cin.get()时C++,我怎么能不限制用户可以输入的字符数
- 我能不能做一个unique_ptr不拥有其尖头对象的所有权
- 类型不完整不允许错误,如何修复
- LNK2005,我不知道我能做些什么来解决这个问题
- 一个C++11数组怎么能不存储它的大小呢
- 怎么能不工作,但马洛克可以
- 能不能回式混?或者变通的解决方案