STL: Stores references or values?

前端 未结 2 2073
悲哀的现实
悲哀的现实 2021-02-07 22:15

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 +

2条回答
  •  庸人自扰
    2021-02-07 22:22

    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 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 v;
    };
    

    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.

提交回复
热议问题