I have a c++ class Foo with an stl std::string as member. Further I have a STL std::vector<Foo> vecFoo containing objects of class Foo by value (not pointers to objects of Foo). Now I was advised by a friend not to implement it in this way but to build the vector with pointers: std::vector<Foo*> or use boost smart pointers. He discussed that a vector, which involves lots of copy operations on its members (allocating more space when adding members etc.) will make problems when the contained classes have dynamic members like std::string. Might there occur any problems?
For my understanding the std::string actually does a deep copy (or copy on write) when class Foo might be copied by the std::vector, as Foo calls copy constructors for all of its members. My friend argued that it is a problem if the string members are of different length among all Foo objects in the vector when the vector is allocating new space. What do you think?
The only reason for using pointers to Foo inside the vector is speed. A pointer to Foo (Foo*) is copied much faster than the complete class Foo, isnt it?
Thx for discussion!
I guess, std::vector with pointers is not going to be more efficient at all if you are going to allocate every element-object with new. But if your element-object is large enough (not becasue of string lengths, but because of its 'non-pointer' members) vector with pointers can perform better or not - it depends on vector reallocation frequency.
Consider the fact that std::vector allocates space logarithmical rarely, becasue it always allocates two times more space than it have allocated previous time.
Things are even better with C++11, where std::vector will use move semantics to avoid for sure copying characters of strings. But you may need to implenent move constructor in your class for this thing to work, if your compiler does not generate default move constructor.
Even before C++11 some std::string implementations used copy-on-write strategy, so just making 'deep copy' of string did not require copying underlying character array unless one of the copies was modified.
it is a problem if the string members are of different length among all Foo objects in the vector
And this is surely non-issue - std::string object, of course, internally holds a pointer to character array, not the array itself.
I am sure, you should analyse your program with profiler before making optimization decisions at such level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With