STL:存储引用或值? [英] STL: Stores references or values?

查看:140
本文介绍了STL:存储引用或值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直对于STL容器(向量,列表,映射...)如何存储值有点困惑。它们是否存储对传入的值的引用,或者它们是否复制/复制construct +存储值本身?

I've always been a bit confused about how STL containers (vector, list, map...) store values. Do they store references to the values I pass in, or do they copy/copy construct +store the values themselves?

例如,

int i;
vector<int> vec;
vec.push_back(i);
// does &(vec[0]) == &i;

class abc;
abc inst;
vector<abc> vec;
vec.push_back(inst);
// does &(vec[0]) == &inst;

感谢

推荐答案

STL容器复制构造和存储你传递的值。如果你想在一个容器中存储对象而不用复制它们,我建议在容器中存储一个指针指向对象:

STL Containers copy-construct and store values that you pass in. If you want to store objects in a container without copying them, I would suggest storing a pointer to the object in the container:

class abc;
abc inst;
vector<abc *> vec;
vec.push_back(&inst);

这是实现容器类的最合理的方法,以防止意外存储对停用堆栈变量的引用帧。请考虑:

This is the most logical way to implement the container classes to prevent accidentally storing references to variables on defunct stack frames. Consider:

class Widget {
public:
    void AddToVector(int i) {
        v.push_back(i);
    }
private:
    vector<int> v;
};

存储对 i 的引用将是危险的因为你将从定义它的方法返回后引用局部变量的内存位置。

Storing a reference to i would be dangerous as you would be referencing the memory location of a local variable after returning from the method in which it was defined.

这篇关于STL:存储引用或值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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