【发布时间】:2012-02-16 00:42:37
【问题描述】:
我使用 new 创建了对象,但是在将它们添加到向量之前取消了对它们的引用。尽管在互联网上拖网,但我无法弄清楚如何在这些项目上调用删除。我只想使用我不想(例如)使用 Boost 库的标准 C++ 和 STL 来做到这一点。
如您所见,a、b 和 c 失去了作用域,剩下的就是我认为是向量中的副本。我该如何删除这些。我不想在数组中存储指针,因为我需要向 API 函数传递一个双精度数组。
请人 - 我如何删除这些对象?
#include <iostream>
#include <vector>
using namespace std;
vector<double> vectorDouble;
void createObjects();
void createObjects() {
double* a=new double(13);
double* b=new double(14);
double* c=new double(15);
//a,b and c are not contiguous memory blocks
cout << "memory location of a: " << a << endl;
cout << "memory location of b: " << b << endl;
cout << "memory location of c: " << c << endl;
vectorDouble.push_back(*a);
vectorDouble.push_back(*b);
vectorDouble.push_back(*c);
}
int main() {
createObjects();
//the memory addresses are contiguous 8 byte chunks
cout << "vector memory at 0: " << &(vectorDouble[0]) << endl;
cout << "vector memory at 1: " << &(vectorDouble[1]) << endl;
cout << "vector memory at 2: " << &(vectorDouble[2]) << endl;
//get pointer to the 2nd element
double *P=&(vectorDouble[1]);
//dereference and look inside - two memory locations both contain the value 14
cout << "vector Pointer P ["<< P <<"] contains " << *P <<endl;
//Which should I call delete on? I have lost reference to the original pointers.
//How should I call delete on the vector?
cout << "deleting pointer that references 2nd vector element" << endl;
delete P; //********* CRASH **********
cout << "Done deleting" << endl;
}
【问题讨论】: