是STL向量调用未分配对象的析构函数吗? [英] Is STL Vector calling a destructor of a not-allocated object?
问题描述
下面的代码显示了不期望的输出:
The folowing code shows an output not expected:
class test
{
public:
test()
{
std::cout << "Created" << (long)this << std::endl;
}
~test()
{
std::cout << "Destroyed" << (long)this << std::endl;
}
};
int main(int argc, char** argv)
{
std::vector<test> v;
test t;
v.push_back(t);
return EXIT_SUCCESS;
}
执行时显示:
Created-1077942161
Destroyed-1077942161
Destroyed674242816
我认为第二个Destroyed输出不应该存在。当我不使用向量时,结果是一个Created和一个Destroyed线如预期。
I think the second "Destroyed" output should not be there. When I don't use the vector the result is one Created and one Destroyed line as expected. Is this behavior normal?
(这是在FreeBSD系统上用GCC编译的)
(This is compiled with GCC on a FreeBSD system)
推荐答案
一切都是应该的:有一个局部变量 t
,它被创建,然后在 main )
,并且有 v [0]
,它在 main()结尾创建和销毁
。
Everything is as it should be: there's the local variable t
, which gets created and then destroyed at the end of main()
, and there's v[0]
, which gets created and destroyed at the end of main()
.
您没有看到创建 v [0]
或移动构造函数,您的测试类不提供。 (因此,编译器为您提供了一个,但没有输出。)
You don't see the creation of v[0]
because that happens by copy or move constructor, which your test class doesn't provide. (So the compiler provides one for you, but without output.)
为了测试的目的,并且对于所有包含所有可能的构造函数,析构函数,赋值和交换运算符的测试类,并在每个中打印一个诊断线,因此您可以看到对象在容器和算法中使用时的行为。
For testing purposes it's handy to write for yourself once and for all a test class that contains all the possible constructors, destructors, assignment and swap operators and prints a diagnostic line in each, so you can witness how objects behave when used in containers and algorithms.
这篇关于是STL向量调用未分配对象的析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!