Ugh, haven't programmed in C++ in forever, simple vector question.

Started by
3 comments, last by xegoth 17 years, 9 months ago
I've been coding in C# for the last year or so and recently returned to C++ only to find I seem to have forgotten everything. Heh. Anyhow... given the following scenario...

class foo
{
list<std::string> m_list;

foo(int Count)
{
     for(int i = 0; i < NumSeats; i++)
     {
         string bar = "something";
	 m_list.push_back(bar);
     }
}

};
Okay. What happens to the data in the list? I want to think that the string is in the scope of the for loop, so it goes out of scope each time around, meaning the list is empty. What *really* happens?
Advertisement
When you insert something into a standard library container, the object is not put into it. Instead a copy of the object is made. Which means that when the string you are inserting into the list goes out of scope you don't have to worry about the string actually in the list, as it is a different object and has not gone out of scope.
m_list is a list of strings.

every time the loop runs, you COPY the string "something" into the last position in the list.

So after the loop has finished, there will be 'NumSeats' string objects, all containing the text "something".


if you wrote it like this:
class foo
{
list m_list;

foo(int Count)
{
for(int i = 0; i <
arg my post got killed coz it treated the > and < as HTML...
Quote:Original post by Will F
When you insert something into a standard library container, the object is not put into it. Instead a copy of the object is made.


Ah, okay. I didn't realize STL makes a copy, the fact that it was passed by reference is what sent me down that path. Thanks.

This topic is closed to new replies.

Advertisement