我试图解决我在c ++中关于类的问题。为了防止复杂的问题,我会为我的问题编写一个示例代码。现在这是我的问题。
class sample1
{
public:
//getter,setter,constructor and destructor functions
private:
string label;
}
class sample2 // in sample2.h #include "sample1" is exist.
{
public:
//getter setter constructors and destructors.
void addSample1(string label);
private:
vector<sample1*> sample1's;
}
现在,正如您所看到的,我想用sample1指针填充sample2类中的向量。我尝试使用以下代码执行此操作但是,显然vector只能存储一个指针,因为在exSample1函数的exacu之后,指针丢失了。这是我的代码不起作用。
void addSample1(string label)
{
sample1 samp1(label);
sample1 * n_pointer=new samp1(label);
n_pointer=&samp1;
sample1's.push_back(n_pointer);
}
有没有人可以帮我解决问题?提前谢谢
答案 0 :(得分:5)
您的addSample
应该只是:
void addSample1(string label)
{
sample1s.push_back(new sample1(label));
}
一旦你完成它们或者在向量中存储智能指针,你必须小心并删除那些指针。
你在addSample
做的事情非常糟糕。
void addSample1(string label)
{
// creates a local sample1 object on the stack
sample1 samp1(label);
//creates a sample1 object on heap
sample1 * n_pointer = new sample1(label);
// overwrites the sample1 pointer with the address of the local object
// this will leak memory as you have lost the pointer to the dynamically allocated object.
n_pointer=&samp1;
//pushes the pointer that points to the local object into the vector
sample1s.push_back(n_pointer);
// here the local object is destroyed so now the pointer in the vector
// points to deallocated space, accessing it will result in undefined behaviour
}
答案 1 :(得分:1)
怎么样
void addSample1(string label)
{
sample1's.push_back(new sample1(label));
}
答案 2 :(得分:1)
这应该有效:
void sample2::addSample1(string label)
{
sample1* n_pointer=new sample1(label);
sample1s.push_back(n_pointer);
}
重命名您的成员变量:
private:
vector<sample1*> sample1s;