std :: vector的复制构造函数如何操作? [英] How does std::vector's copy constructor operate?
问题描述
std :: vector< std :: string>
如何在调用以下代码时初始化其自身
How does a std::vector<std::string>
initialize its self when the following code is invoked
std::vector<std::string> original;
std::vector<std::string> newVector = original;
看起来好像复制构造函数将在 std :: vector< std :: string>在
newVector = original
期间新的,但是如何引入 std :: string
覆盖 orginal
?它们是副本还是新的 std :: string
的?所以是 newVector [0]
中的内存与 original [0]
相同。
It would seem as if the copy constructor would be invoked on std::vector<std::string> new
during 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]
.
我问的原因是我做了以下的事情:
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();
}
t
超出范围的 DoStuff
(在非优化构建),但如果 t
只是填充指针 std :: string
在 globalVector
中,可能会调用析构函数并使用 std :: string
删除,用于使全局变量[0]
填充垃圾 std :: string
'
t
will fall out of scope of DoStuff
(on a non optimized build), but if it t
is just filled with pointers to the std::string
's in globalVector
, might the destructor be called and the memory used in std::string
deleted, there for making globalVector[0]
filled with garbage std::string
's after DoStuff
is called?
一个坚果壳,我基本上是问,当 std :: vector
的复制构造函数,如何复制其中的元素?
A nut shell, I am basically asking, when std::vector
's copy constructor is called, how are the elements inside copied?
推荐答案
std :: vector
和大多数其他标准库容器按值存储元素。插入时或复制容器时复制元素。 std :: string
也维护自己的数据副本,就您的使用而言。
std::vector
and most other standard library containers store elements by value. The elements are copied on insertion or when the container is copied. std::string
also maintains its own copy of the data, as far as your usage of it is concerned.
这篇关于std :: vector的复制构造函数如何操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!