Student class with std::string I am writing a class that has a few std::string as a member. I can't find clear guidelines on how use them in a safe way. Are std::string any different then int when we are talking about class members? Do I initialize the strings in the correct way? (How) can I improve the constructor?

#include &lt;string&gt;
#include &lt;iostream&gt;

class Student {
public:
    std::string name;
    Student(std::string name) {
        this-&gt;name = name;
    }
};

int main() {
    std::string name1 = "john";
    Student student1(name1);
    name1 = "jenny";
    std::cout &lt;&lt; student1.name &lt;&lt; std::endl;
    {
        std::string name2 = "ashley";
        student1.name = name2;
        name2 = "remy";
    }
    std::cout &lt;&lt; student1.name &lt;&lt; std::endl;
    return 0;
}


Which gave the following output as intended:


  john 
  ashley
Consider replacing this:

Student(std::string name) {
    this-&gt;name = name;
}


with one of these two:

Student(std::string n)
: name{ std::move(n) } // assign here, not in function body
{
}

Student(const std::string&amp; n)
: name(n) // assign here, not in function body
{
}


They are more efficient and more idiomatic.

The first takes the argument by value (constructs a string copy when it receives an argument) , then moves the constructed value into Student::name.

The second is marginally faster than the first (but this speed difference should not matter in most use cases, so which you choose is a matter of style), but it doesn't express as well as the first, the idea that Student gets it's own copy of the string (passing by value means "the function gets it's own copy of the value", or "the function takes ownership of the argument").