Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

c++ - std::string in struct - Copy/assignment issues?

Suppose I have a struct containing a std::string, like this:

struct userdata{
        int uid;
        std::string username;
    }

Do I need to create a copy ctor or anything to return it from a function or to use it inside a STL container? Consider this function:

userdata SomeClass::GetUserData(unsigned int uid)
{
    //do error checking and other stuff...
    //m_usermap is std::map<unsigned int, userdata>
    return m_usermap[uid];
}

When I insert userdata structs into the std::map, a copy of the struct gets created, right? Does a new std::string get created using the value of the username field, or does some sort of bitwise copy happen (this would be bad)? Similarly, when I return a userdata struct from the GetUserData method, does it have an independent string holding the username or do I need to define a copy ctor and explicitly create a new string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't have to do anything special. C++ (and the implementation of STL) define this to just work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...