Hello,
I'm just starting to learn C++, coming from a Java / bit of C background. I have some questions about how vectors of objects and pointers work in C++.
Say I want to create a vector of SomeClass objects, and the SomeClass constructor takes one argument. However, SomeClass is not copyable, so I can't do something like:
So instead, I used a temporary variable and stored pointers inside the vector instead:
However, all the pointers in someVector ended up pointing to temp(args[args.size()-1]). I've resolved this by using boost::shared_p tr instead, but I wanted to understand why the above code didn't work as expected. I thought that in each iteration of the for loop, a new temp will get created, and a reference to it will be stored in someVector (so that it won't garbage collected or w/e since there's still a reference to it). The same thing also seems to happen when I make a vector of a struct...
From general Googling, I get the feeling that in general, it's probably a good idea to get into the habit of storing pointers instead of actual objects and structs in vectors - so I should probably get used to using vectors of shared_ptr?
Also, any other general comments, tips, common gotchas, etc. will be greatly appreciated (trying to learn all I can!).
Thanks!
I'm just starting to learn C++, coming from a Java / bit of C background. I have some questions about how vectors of objects and pointers work in C++.
Say I want to create a vector of SomeClass objects, and the SomeClass constructor takes one argument. However, SomeClass is not copyable, so I can't do something like:
Code:
vector<SomeClass> someVector; for (int i=0; i<args.size(); i++){ someVector.push_back( SomeClass(args[i]) ) }
Code:
vector<SomeClass *> someVector; for (int i=0; i<args.size(); i++){ SomeClass temp(args[i]); someVector.push_back(&temp); }
From general Googling, I get the feeling that in general, it's probably a good idea to get into the habit of storing pointers instead of actual objects and structs in vectors - so I should probably get used to using vectors of shared_ptr?
Also, any other general comments, tips, common gotchas, etc. will be greatly appreciated (trying to learn all I can!).
Thanks!
Comment