Vectors & Passing Objects

1
2
ServiceProvider mySP(spUserName, spPassword);
mySPs.push_back(mySP);

vs.
mySPs.push_back(ServiceProvider (spUserName, spPassword));

My Questions:
1) Will the second method work?
2) mySP is a temporary object, when I push it into the vector mySPs will a new object be copied into the vector? The reason why I am asking is because since mySP is temporary it will be destroyed, I want to make sure when I call mySPs from another class mySP will still exist.

Thanks
1) Will the second method work?
Yes. Both put a copy onto the end of the vector.

2) mySP is a temporary object, when I push it into the vector mySPs will a new object be copied into the vector?
As above, yes.

The reason why I am asking is because since mySP is temporary it will be destroyed, I want to make sure when I call mySPs from another class mySP will still exist.
I don't know what you mean.

The reason why I am asking is because since mySP is temporary it will be destroyed, I want to make sure when I call mySPs from another class mySP will still exist


You will still be able to access it, you do not have to worry because the vector will make its own copy. Actually the second method is preferred in large applications where you might be making this function call regularly bc compilers can optimize out the creation of the temporary.

Quick bit of advice, this is a very simple problem to test on your own. You will develop a better understanding of C++ by taking a little bit of time and figuring it out on your own and then come to the message boards for why things are better done certain ways like the aforementioned compiler optimization situation
Thanks guys!

Great answers :)
Topic archived. No new replies allowed.