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

前端 未结 4 809
甜味超标
甜味超标 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:58

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 11:02

    std::string is reference-counted, and its copy constructor takes place. So nothing to worry about. Everything is handled correctly.

    0 讨论(0)
  • 2020-12-19 11:02

    As long as you don't have pointers as your datamembers, you should be fine.

    0 讨论(0)
提交回复
热议问题