1

我试图解决我关于 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 只能存储一个指针,因为在执行 addSample1 函数后,指针丢失。这是我的代码不起作用。

void addSample1(string label)
{       
        sample1  samp1(label);
    sample1 * n_pointer=new samp1(label);
    n_pointer=&samp1;
    sample1's.push_back(n_pointer);
}

有没有人可以帮助我解决我的问题?提前致谢

4

3 回答 3

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
}
于 2013-05-10T21:19:40.877 回答
1

怎么样

void addSample1(string label)
{       
    sample1's.push_back(new sample1(label));
}
于 2013-05-10T21:18:16.280 回答
1

这应该有效:

void sample2::addSample1(string label)
{       
    sample1* n_pointer=new sample1(label);
    sample1s.push_back(n_pointer);
}

重命名您的成员变量:

private:
  vector<sample1*> sample1s;
于 2013-05-10T21:21:18.163 回答