为什么当我添加实例到一个向量时,我的类的析构函数被调用? [英] Why does my class's destructor get called when I add instances to a vector?
问题描述
看来每次向向量m_test添加一个对象时,都会调用destructor方法。我缺少什么?如何防止这种情况的发生?
It seems that every time I add an object to the vector m_test, the destructor method is called. Am I missing something? How can I prevent this from happening?
class TEST
{
public:
TEST();
~TEST();
int * x;
};
TEST::TEST()
{
}
TEST::~TEST()
{
... it is called every time I push_back something to the vector ...
delete x;
}
vector<TEST> m_test;
for (unsigned int i=0; i<5; i++)
{
m_test.push_back(TEST());
}
推荐答案
违反了三项规则。你的类有一个析构函数,所以你需要一个复制构造函数和赋值运算符。或者,您不能允许复制您的类(例如通过使 T(T const&)
和 T& operator = )
private,或者通过派生 boost :: noncopyable
),然后重新调整向量,而不是使用 push_back
。
The problem here is that you're violating the Rule of Three. Your class has a destructor so you need a copy-constructor and an assignment operator, too. Alternatively, you could not allow your class to be copied (for example by making T(T const&)
and T& operator=(T const&)
private, or by deriving from boost::noncopyable
), and then resize the vector instead of using push_back
.
在第一种情况下,你可以像平常一样只需 push_back
第二,语法将像
In the first case, you can just push_back
your class as you usually would. In the second, the syntax would be something like
std::vector<TEST> vec(5);
// vec now has five default-constructed elements of type TEST.
没有做这些事情是一个坏主意,因为你很可能会遇到双删除即使你认为你永远不会复制或分配 TEST
其中 x!= nullptr
,它显然禁止它是更安全的。
Not doing either of these things is a bad idea, as you are very likely to run into double deletion issues at some point -- even if you think you'll never copy or assign a TEST
where x != nullptr
, it's much safer to explicitly forbid it.
顺便说一下,如果你有成员指针,当一个对象超出范围应该删除,请考虑使用智能指针 scoped_ptr
, unique_ptr
和 shared_ptr
$ c> auto_ptr 如果您无法使用Boost或C ++ 11)。
By the way, if you have member pointers that should be deleted when an object goes out of scope, consider using smart pointers like scoped_ptr
, unique_ptr
and shared_ptr
(and maybe auto_ptr
if you're unable to use Boost or C++11).
这篇关于为什么当我添加实例到一个向量时,我的类的析构函数被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!