Sign in to follow this  

(C++) std::vector, std::string and structures (Solved)

This topic is 4715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I create a container of structures which have std::strings in them, will the std::strings be deep copied or shallow copied? Or do I have to convert it into a class and provide a deep copy constructor? Edit: (Solved) [Edited by - MENTAL on January 17, 2005 2:50:01 PM]

Share this post


Link to post
Share on other sites
This code is standards compliant:


struct Emp
{
std::string firstName;
std::string lastName;
std::string position;
};

std::list<Emp> employeeList;

Emp e;
e.firstName = "John";
e.lastName = "Doe";
e.position = "Cashier";

employeeList.push_back(e);

e.firstName = "Bob";
e.lastName = "Smith";
e.position = "Bag boy";

employeeList.push_back(e);



The reason for that is that if you do not provide a copy constructor, then c++ will create a default copy ctor which consists of calling the copy ctor of all the members.

Share this post


Link to post
Share on other sites
in general when using the STL, everything is deep copied unless you specifically pass the STL structures by reference or by pointer. so functions like this are generally bad:


void doSomething( std::vector< MyClass > allMyClasses )
{
}





the vector used inside of doSomething will be a complete copy of the vector that was passed in. in your case you'd be deep copying everything: the vector and all the strings it contains.

-me

Share this post


Link to post
Share on other sites

This topic is 4715 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this