C++ std::vector 的复制构造函数如何操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10368602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:57:55  来源:igfitidea点击:

How does std::vector's copy constructor operate?

c++stringvectorstd

提问by chadb

How does a std::vector<std::string>initialize its self when the following code is invoked

std::vector<std::string>调用以下代码时如何初始化自身

std::vector<std::string> original;
std::vector<std::string> newVector = original;

It would seem as if the copy constructor would be invoked on std::vector<std::string> newduring newVector = original, but how are the std::string's brought over inside of the orginal? Are they copies or new std::string's? So is the memory in newVector[0]the same as original[0].

看起来好像复制构造函数会在std::vector<std::string> newduring上被调用newVector = original,但是std::string's是如何被引入到 中的orginal?他们是副本还是新std::string的?内存newVector[0]也是如此original[0]

The reason I ask is say I do the following

我问的原因是说我做了以下事情

#include <vector>
#include <string>
using namespace std;

vector<string> globalVector;

void Initialize() {
    globalVector.push_back("One");
    globalVector.push_back("Two");
}

void DoStuff() {
    vector<string> t = globalVector;
}

int main(void) {
    Initialize();
    DoStuff();
}

twill fall out of scope of DoStuff(on a non optimized build), but if it tis just filled with pointers to the std::string's in globalVector, might the destructor be called and the memory used in std::stringdeleted, there for making globalVector[0]filled with garbage std::string's after DoStuffis called?

t就会掉出来的范围DoStuff(在非优化的版本),但如果它t只是充满了指针指向std::string的中globalVector,可能会在析构函数被调用,并在使用的内存std::string中删除,也用于制作globalVector[0]堆满了垃圾std::string的后DoStuff是叫?

A nut shell, I am basically asking, when std::vector's copy constructor is called, how are the elements inside copied?

一个坚果壳,我基本上是在问,当std::vector调用 的复制构造函数时,里面的元素是如何复制的?

回答by Dark Falcon

std::vectorand most other standard library containers store elements by value. The elements are copied on insertion or when the container is copied. std::stringalso maintains its own copy of the data, as far as your usage of it is concerned.

std::vector和大多数其他标准库容器按值存储元素。在插入或复制容器时复制元素。std::string还维护自己的数据副本,就您对数据的使用而言。