tamirvs
asked on
something weird in vector
look at this code:
---------------------
string s = "abc";
vector<string> v;
v.push_back(s);
v.clear();
cout<<v[0];
---------------------
I'm creating a vector and assigning to its first element the string s.
then I use clear() to empty the vector.
I expected v[0] to be empty but when i print it, it prints "abc", why is that? shouldn't it makes the program crash or something?
---------------------
string s = "abc";
vector<string> v;
v.push_back(s);
v.clear();
cout<<v[0];
---------------------
I'm creating a vector and assigning to its first element the string s.
then I use clear() to empty the vector.
I expected v[0] to be empty but when i print it, it prints "abc", why is that? shouldn't it makes the program crash or something?
This is an unpredictable behaviour, you have to avoid to go out of vector bounds by yourself.
You are absolutely right that this should crash.
If you empty the vector and clear() does that
then accessing the content is of course illegal.
The above doesn't work in
MS Visual Studio .net Debug or Release compilation.
Not all compilers strictly abide the rules. I am not
saying that VS does (MS usually doesn't, does it?)
But in this case it does and it seems to be
a compiler issue to me.
If you empty the vector and clear() does that
then accessing the content is of course illegal.
The above doesn't work in
MS Visual Studio .net Debug or Release compilation.
Not all compilers strictly abide the rules. I am not
saying that VS does (MS usually doesn't, does it?)
But in this case it does and it seems to be
a compiler issue to me.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I know, i'm just curious why it happens.
ASKER
my previous reply was addressed to jaime, only now i see the other 2 replies =/
>>BTW. Typically, collection implementations (specially arrays or 'vectors'), doesn't deallocate its memory inmediatly when you erase an element, for performance purposes.
maybe this is the cause?
>>BTW. Typically, collection implementations (specially arrays or 'vectors'), doesn't deallocate its memory inmediatly when you erase an element, for performance purposes.
maybe this is the cause?
I think this is the most possible cause. Try with a more simple vector, let's say, vector<int>
ASKER
I'm getting the same problem with int, char*, everything...
well, then it is the cause, but as I have said, this is an unpredictable result, you can get a different behaviour with another compiler, and finally you are responsible for not accessing vector out of bounds.
try
vector<string> v;
cout << v[0];
to find out if you will ever get an error message.
vector<string> v;
cout << v[0];
to find out if you will ever get an error message.
ASKER
this one makes my program crash...
that's because tipically (but not mandatory) when a vector is new, it doesn't allocate space until it receive first element.