今天我回去調查了一箇舊項目中遇到的錯誤。這不完全是一個錯誤,相反,我不知道如何去做我需要做的事情。不要真的想進入項目的細節,因爲它是舊的,越野車,低效率,更重要的是無關緊要。所以我編碼了一個新的示例代碼:指針複製到範圍外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) - 比某種東西或其他東西好得多。 –