【发布时间】:2015-12-06 08:11:06
【问题描述】:
今天我回去调查我在一个旧项目中遇到的一个错误。这不完全是一个错误,而是我不知道该怎么做我需要做的事情。不要真的想深入了解项目的细节,因为它老旧、有缺陷、效率低下,更重要的是无关紧要。所以我编写了一个新的示例代码:
#include <iostream>
#include <vector>
#include <time.h>
#include <random>
#include <string>
class myDoc;
class myElement
{
int myInt;
std::string myString;
myElement * nextElement;
//a pointer to the element that comes immediately after this one
public:
myElement(int x, std::string y) : myInt(x), myString(y){};
friend myDoc;
};//an element type
class myDoc
{
std::vector<myElement> elements;
public:
void load();
~myDoc()
{
//I believe i should delete the dynamic objects here.
}
};// a document class that has bunch of myElement class type objects as members
void myDoc::load()
{
srand(time(0));
myElement * curElement;
for (int i = 0; i < 20; i++)
{
int randInt = rand() % 100;
std::string textInt = std::to_string(randInt);
curElement = new myElement(randInt,textInt);
//create a new element with a random int and its string form
if (i!=0)
{
elements[i-1].nextElement = curElement;
//assign the pointer to the new element to nextElement for the previous element
//!!!!!!!!!!!! this is the part that where i try to create a copy of the pointer
//that goes out of scope, but they get destroyed as soon as the stack goes out of scope
}
elements.push_back(*curElement);// this works completely fine
}
}
int main()
{
myDoc newDoc;
newDoc.load();
// here in newDoc, non of the elements will have a valid pointer as their nextElement
return 0;
}
基本概要:我们有一个文档类型,它由我们定义的元素类型的向量组成。在这个例子中,我们将 20 个随机动态分配的新元素加载到文档中。 我的问题/问题:
-
void myElement::load()函数结束时,指针和/或其副本超出范围并被删除。我如何保持一份至少在它指向的对象被删除之前保持不变(不是完全静态的,是吗?)? -
elements向量中的对象是原始动态分配的对象还是只是一个副本? - 我用
new分配内存,我应该如何/何时应该delete他们?
【问题讨论】:
-
请发帖a Minimal, Complete, and Verifiable example - 比某物或其他的图片要好得多。