Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL: Stores references or values?

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?

For example,

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

and

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

Thanks

like image 216
jameszhao00 Avatar asked Sep 05 '09 06:09

jameszhao00


People also ask

What is reference type in c++?

There are two kinds of references: lvalue references which refer to a named variable and rvalue references which refer to a temporary object.

When to use c++ reference?

Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

What are objects that contain other objects with values eg vector set map?

A container is a holder object that stores a collection of other objects (its elements).


2 Answers

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

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.

like image 160
Michael Koval Avatar answered Nov 15 '22 18:11

Michael Koval


That depends on your type. If it's a simple value type, and cheap to copy, then storing values is probably the answer. On the other hand, if it's a reference type, or expensive to copy, you'd better store a smart pointer (not auto_ptr, since its special copy semantics prevent it from being stored in a container. Go for a shared_ptr). With a plain pointer you're risking memory leakage and access to freed memory, while with references you're risking the latter. A smart pointer avoids both.

like image 45
On Freund Avatar answered Nov 15 '22 17:11

On Freund