今天我回去调查了一个旧项目中遇到的错误。这不完全是一个错误,相反,我不知道如何去做我需要做的事情。不要真的想进入项目的细节,因为它是旧的,越野车,低效率,更重要的是无关紧要。所以我编码了一个新的示例代码:指针复制到范围外C++
#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
?
这是我画的第一个问题(对于具体例子不是很准确,但问题是相同的),并感谢您的时间。
请发布[最小,完整和可验证的示例](http://stackoverflow.com/help/mcve) - 比某种东西或其他东西好得多。 –