为什么emplace_back()的行为如此? [英] Why is emplace_back() behaving like this?

查看:61
本文介绍了为什么emplace_back()的行为如此?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 为什么在调用emplace_back()之后立即调用〜Base()
  2. 为什么在析构函数调用后可以访问sayHello()
  3. 为什么〜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()的调用起作用的原因.

In the call vBase.emplace_back ( Base() ); you first create a Base object. The vector creates another Base in place and the resources owned by the first Base are then moved into the new one. The first base is then deleted. Inside your vector you now have a moved constructed Base which is why the call to sayHello() works.

您可能想要做的是让 emplace_back 实际上在适当的位置构造对象,而无需手动创建临时对象.通过仅提供构造 Base 所需的参数来做到这一点.像这样:

What you probably want to do is to let emplace_back actually construct the object, in place without creating a temporary object manually. You do that by only supplying the arguments needed to construct a Base. Like so:

vBase.emplace_back();

这篇关于为什么emplace_back()的行为如此?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆