【问题标题】:Creating C++ STL Vector on heap of given size inside constructor [duplicate]在构造函数内给定大小的堆上创建 C++ STL 向量 [重复]
【发布时间】: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

http://ideone.com/WbCxaR

我预计 Ex 大小为 10,而不是在堆上创建向量的堆内存地址。我在这里做错了什么?

【问题讨论】:

  • myVec 在您执行此操作时已被删除:V v(myVec-&gt;size());。但是你为什么要使用指针和new?你真的不需要。
  • “我在这里做错了什么” - 调用未定义的行为。您正在取消引用一个悬空指针。它处理的对象已被删除。
  • 好吧,这是一个愚蠢的问题。我没注意

标签: c++ vector stl heap-memory


【解决方案1】:

仅仅因为你试图从已经释放的指针中获取size。不正确,v构造后才删除myVec。

其实这个程序根本不需要指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2017-03-27
    • 2015-06-15
    相关资源
    最近更新 更多