标准库容器结构是否存储副本或引用?
Do standard library containers structures store copies or references?
恐怕标准库容器会在其内部存储我放入其中的所有元素的副本。我希望他们使用指向我的元素的引用或指针,这样他们就不会浪费额外的内存和时间来复制每个元素。我做了这个证明:
queue<int> prueba;
int x = 5;
prueba.push(x);
x++;
cout << prueba.front() << ", ";
cout << x;
prueba.pop();
结果是:5、6。
所以,如果我做一个有很多重成员的大 class,然后,我将那个 class 的很多对象推入一个标准库容器中。
容器会复制里面的每个对象吗?这太可怕了!
除了只创建指针容器之外,还有什么方法可以避免这种灾难性的结局吗?
您问题的答案很简单:STL 容器存储副本。
- Does STL structures stores copies or references?
C++ 标准容器是非侵入式容器
,因此它们具有以下属性:
Object doesn't "know" and contain details about the container in which is to be stored. Example:
struct Node
{
T data;
}
1. Pros:
- does not containe additional information regarding the container integration.
- object's lifetime managed by the container. (less complex.)
2. Cons:
- store copies of values passed by the user. (inplace
emplace
construction possible.)
- an object can belong only to one container. (or the contaier should store pointers to objects.)
- overhead on storing copies. (bookkeeping on each allocation.)
- can't store derived object and still maintain its original type. (slicing - looses polymorphism.)
因此,您问题的答案是 - 他们存储副本。
- Is there any way to avoid this catastrophic end, other than create just containers of pointers?
据我所知,一个合理的解决方案是智能指针的容器。
恐怕标准库容器会在其内部存储我放入其中的所有元素的副本。我希望他们使用指向我的元素的引用或指针,这样他们就不会浪费额外的内存和时间来复制每个元素。我做了这个证明:
queue<int> prueba;
int x = 5;
prueba.push(x);
x++;
cout << prueba.front() << ", ";
cout << x;
prueba.pop();
结果是:5、6。
所以,如果我做一个有很多重成员的大 class,然后,我将那个 class 的很多对象推入一个标准库容器中。
容器会复制里面的每个对象吗?这太可怕了!
除了只创建指针容器之外,还有什么方法可以避免这种灾难性的结局吗?
您问题的答案很简单:STL 容器存储副本。
- Does STL structures stores copies or references?
C++ 标准容器是非侵入式容器
,因此它们具有以下属性:Object doesn't "know" and contain details about the container in which is to be stored. Example:
struct Node { T data; }1. Pros:
- does not containe additional information regarding the container integration.
- object's lifetime managed by the container. (less complex.)
2. Cons:
- store copies of values passed by the user. (inplace
emplace
construction possible.)- an object can belong only to one container. (or the contaier should store pointers to objects.)
- overhead on storing copies. (bookkeeping on each allocation.)
- can't store derived object and still maintain its original type. (slicing - looses polymorphism.)
因此,您问题的答案是 - 他们存储副本。
- Is there any way to avoid this catastrophic end, other than create just containers of pointers?
据我所知,一个合理的解决方案是智能指针的容器。