我试图解决我在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;
}
Run Code Online (Sandbox Code Playgroud)
现在,正如您所看到的,我想用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);
}
Run Code Online (Sandbox Code Playgroud)
有没有人可以帮我解决问题?提前致谢
你addSample应该只是:
void addSample1(string label)
{
sample1s.push_back(new sample1(label));
}
Run Code Online (Sandbox Code Playgroud)
并且一旦完成它们就必须小心并删除这些指针,或者将智能指针存储在向量中.
你在做什么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
}
Run Code Online (Sandbox Code Playgroud)