[英]put pointer in std::vector & memory leak
class A {
public:
void foo()
{
char *buf = new char[10];
vec.push_back(buf);
}
private:
vector<char *> vec;
};
int main()
{
A a;
a.foo();
a.foo();
}
在class A
, foo()
分配一些内存,并将指针保存到vec
。 当main()
完成时, a
将解构,a.vec也将a.vec
,但是分配的内存会被释放吗?
内存将不会被释放。 要发布它,您需要将其放在unique_ptr或shared_ptr中。
class A {
public:
void foo()
{
unique_ptr<char[]> buf(new char[10]);
vec.push_back(buf);
}
private:
vector<unique_ptr<char[]>> vec;
};
或者你可以做一个破坏者
~A()
{
for(unsigned int i =0; i < vec.size(); ++i)
delete [] vec[i];
}
编辑
如前所述,您还需要进行复制和分配(如果您打算使用它们的话)
class A
{
public:
A& operator=(const A& other)
{
if(&other == this)
return *this;
DeepCopyFrom(other);
return *this;
}
A(const A& other)
{
DeepCopyFrom(other);
}
private:
void DeepCopyFrom(const A& other)
{
for(unsigned int i = 0; i < other.vec.size(); ++i)
{
char* buff = new char[strlen(other.vec[i])];
memcpy(buff, other.vec[i], strlen(other.vec[i]));
}
}
std::vector<char*> vec;
};
有关深度复制主题以及为何在这里需要它的更多信息
http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.