【发布时间】:2015-10-26 07:21:01
【问题描述】:
我想测试一下c++中的delete能做什么,所以写了如下:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A(string s):a(s){}
string getS(){
return a;
}
private:
string a;
};
class B{
public:
B(string str):s(str){}
void setV(A a){
v.push_back(a);
}
string getS(){
return s;
}
private:
vector<A> v;
string s;
};
int main(){
A a("abc");
B* b = new B("cba");
b->setV(a);
cout<<b->getS()<<endl;
cout<<a.getS()<<endl;
delete b;
cout<<b->getS()<<endl;
cout<<a.getS()<<endl;
return 0;
}
我仍然得到以下输出:
cba
abc
cba
abc
看起来我仍然可以访问 a 和 b 的内存? 所以我的问题是 1.为什么我可以访问b,因为我已经调用了delete? 2.为什么我可以访问a,因为调用了b的析构函数,所以包含a的向量的内存应该是空闲的?
干杯
【问题讨论】:
-
重复问题。您通过访问已删除的内存来调用“未定义的行为”。
-
未定义的行为是未定义的。您并没有从计算机中物理删除字节 - 您只是放弃了所有权。
标签: c++ memory-management destructor