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

前端 未结 4 816
甜味超标
甜味超标 2020-12-19 10:10

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

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

Do I nee

4条回答
  •  庸人自扰
    2020-12-19 10:59

    std::strings by themselves can be copied without any problems.

    When you define a class (or struct), C++ will generate a number of methods for you by default, including a copy constructor and an assignment operator. I believe that the generated copy constructor will call the copy constructor on each of fields, and the generated assignment operator will call the assignment operator on each of the fields. As your userdata struct is copied, std::string's copy constructor will be called for the username field.

    The STL containers and algorithms should use some combination of the copy constructor and the assignment operator, so this should all be fine.

提交回复
热议问题