【发布时间】:2015-02-19 08:22:54
【问题描述】:
我对以下代码的输出感到很困惑:
#include <cmath>
#include <vector>
#include <iostream>
class V
{
std::vector<int> *ex_;
public:
V( std::vector<int>::size_type sz );
~V();
};
V::V( std::vector<int>::size_type sz )
{
// Why this doesn't work ??
ex_ = new std::vector<int>( sz );
std::cout<< "Ex size:" <<ex_->size() << std::endl;
}
V::~V()
{
delete ex_;
}
int main()
{
// This works
std::vector<int> *myVec = new std::vector<int>(10);
std::cout << "Vector size:" << myVec->size() << std::endl;
delete myVec;
// Why this doesn't work ??
V v(myVec->size());
return 0;
}
输出:
矢量大小:10
Ex 尺寸:34087952
我预计 Ex 大小为 10,而不是在堆上创建向量的堆内存地址。我在这里做错了什么?
【问题讨论】:
-
myVec在您执行此操作时已被删除:V v(myVec->size());。但是你为什么要使用指针和new?你真的不需要。 -
“我在这里做错了什么” - 调用未定义的行为。您正在取消引用一个悬空指针。它处理的对象已被删除。
-
好吧,这是一个愚蠢的问题。我没注意
标签: c++ vector stl heap-memory