- 为什么 ~Base() 在调用 emplace_back() 之后立即被调用
- 为什么在析构函数调用后可以访问 sayHello()
- 为什么 ~Base() 再次被调用
#include <iostream>
#include <vector>
class Base
{
private:
static int m_count;
public:
Base()
{
std::cout << " Base created. Count = " << ++m_count << std::endl;
}
~Base()
{
std::cout << " Base destroyed. Count = " << --m_count << std::endl;
}
void sayHello() const
{
std::cout << " Base says hello" << std::endl;
}
};
int Base::m_count = 0;
int main()
{
{
std::vector< Base > vBase;
vBase.emplace_back ( Base() ); // <- Why does ~Base() get called here
vBase[0].sayHello(); // <- Why is this function accessible after call to dtor
}
return 0;
}
程序输出...
Base created. Count = 1
Base destroyed. Count = 0
Base says hello
Base destroyed. Count = -1
在通话中vBase.emplace_back ( Base() );
你首先创建一个Base
目的。该向量创建了另一个向量Base
到位以及第一方拥有的资源Base
然后搬进新的。然后删除第一个碱基。在你的向量中你现在有一个移动的构造Base
这就是为什么要调用sayHello()
works.
你可能想做的是让emplace_back
实际上就地构造对象,而无需手动创建临时对象。您只需提供构造一个所需的参数即可做到这一点Base
。就像这样:
vBase.emplace_back();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)