Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ containers behavior

Tags:

c++

containers

My question is simple. When I use STL containers, do they copy the value I store there (by using copy constructor) or not? What if I give them array of characters (char *) instead of string instance? How do they behave? Is guaranteed that information will be stored in heap instead of system stack?

Thanks for answers.

like image 651
Rusty Horse Avatar asked Feb 02 '10 21:02

Rusty Horse


2 Answers

Values in STL containers are stored by-value. If you have a vector like this:

class BigObject
{
...
};

vector<BigObject> myObjs;
myObjs.push_back(obj1);
myObjs.push_back(obj2);
...

The vector will make a copy of the object you're pushing in. Also in the case of a vector, it may make new copies later when it has to reallocate the underlying memory, so keep that in mind.

The same thing is true when you have a vector of pointers, like vector<char*> -- but the difference here is that the value that is copies is the pointer, not the string it points to. So if you have:

vector<char*> myStrings;
char* str = new char[256];     // suppose str points to mem location 0x1234 here
sprintf(str, "Hello, buffer");
myStrings.push_back(str);
delete [] str;

...the vector will get a copy of the pointer. The pointer it gets will have the same value (0x1234), and since you deleted that pointer after pushing in the pointer, your vector contains a wild pointer and your code will eventually crash (sooner than later, hopefully).

Which, by the way, could have been avoided if instead of using char*s you used strings:

typedef vector<string> strings;
strings myStrings;
myStrings.push_back("Hello, buffer");
like image 89
John Dibling Avatar answered Oct 19 '22 12:10

John Dibling


They copy the value. Most (all?) containers require that a copy constructor and an assignment operator are defined.

If you give them a char*, they copy the pointer, not the value pointed to. So then it would be your responsibility to make sure that the string itself is not destroyed while it is still in use, and gets destroyed when it is no longer necessary.

like image 44
Thomas Avatar answered Oct 19 '22 12:10

Thomas