在构造函数中给定大小的堆上创建 C++ STL Vector

Creating C++ STL Vector on heap of given size inside constructor

我对以下代码的输出感到很困惑:

#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;
}

输出:

Vector size:10

Ex size:34087952

http://ideone.com/WbCxaR

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

只是因为您正试图从已释放的指针中获取 size。不对,v构造后才删除myVec

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