std :: string in struct - 复制/赋值问题? [英] std::string in struct - Copy/assignment issues?
问题描述
假设我有一个包含std :: string的结构,如下所示:
Suppose I have a struct containing a std::string, like this:
struct userdata{
int uid;
std::string username;
}
我需要创建一个复制的ctor或任何东西,或者在STL容器中使用它?考虑这个函数:
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];
}
当我将userdata结构体插入std :: map时, struct被创建,对吧?是否使用username字段的值创建了一个新的std :: string,或者做某种按位复制(这将是坏的)?类似地,当我从GetUserData方法返回一个userdata结构时,它是否有一个独立的字符串保存用户名或者我需要定义一个复制ctor并显式创建一个新的字符串?
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?
推荐答案
std :: string 是引用计数,并且其复制构造函数发生。所以没有什么可担心的。一切都得到正确处理。
std::string is reference-counted, and its copy constructor takes place. So nothing to worry about. Everything is handled correctly.
这篇关于std :: string in struct - 复制/赋值问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!