在函数c++中插入向量后对象会发生什么

问题描述 投票:0回答:1

当您在代码块内声明变量时,该变量的生命周期将持续到代码块结束为止。当变量的生命周期结束时,即控制退出该块时,该变量将被销毁。

但是在 std::vector、std::map 的情况下...... 当我进行这种push_back(, insert( 当使用局部变量执行此操作时,它是复制对象还是只是获取它的引用?

参见下面的示例,在 list.push_back(a); 行上

我在控制台看到的是

txt_0
txt_1
txt_2

代码:

#include <iostream>
#include <vector>
#include <sstream>

using std::iostream;

class A {
public:
    std::string txt;
};

class T {
public:
    std::vector<A> list;

    void test()
    {
        for (int i = 0; i < 3; i++) 
        {
            A a;
            a.txt = "txt_" + std::to_string(i);
            list.push_back(a);
        }
    }

    void show() 
    {
        for (int i = 0; i < list.size(); i++) 
        {
            std::cout << list[i].txt << std::endl;
        }
    }
};

int main()
{
    T t;
    t.test();
    t.show();
}
c++ c++11 vector
1个回答
0
投票

push_back 上的

文档
对此相当清楚。

将给定的元素值附加到容器的末尾。

  1. 新元素被初始化为值的副本。
  2. 值被移动到新元素中。
© www.soinside.com 2019 - 2024. All rights reserved.