I am writing a class that has a few std::string as member. I can't find clear guidelines how use them in a safe way.
As long as you are not using new/delete their usage is by default safe.
Are std::string any different then int when we are talking about class members?
Any well constructed C++ class should behave just like a normal built in type (and everything in the standard is well constructed). As long as you don't use new/delete it should feel no different to you than using a built in type.
Do I initialize the strings in the correct way?
Its not going to break anything but it could be better.
(How) can I improve the constructor?
class Student {
public:
std::string name;
Student(std::string name) {
this->name = name;
}
};
Try not to use this->
This is a red flag.
- You are either using it to be redundant
Don't boither most C++ programers don't use it.
- Or you need to use it to disambiguate local from member variables.
If this is the case you are shadowing member variables which is dangerous. Turn on your compiler warnings and don't shadow variables as this will lead to situations where you accidentally use the wrong one.
Prefer to use the initializer list
All the members of a class are constructed before the body of the constructor is executed. So in your case you are constructing the name
member then (in the body) calling the assignment operator. If you use the initializer list you construct the member using the parameter.
class Student {
public:
std::string name;
Student(std::string const& name)
: name(name)
{}
};
Move constructor
In the latest version of the standard we have introduced the concept of Move construction. This is advanced so ignore it for now if you are learning. But it allows for a more efficient form of construction (as the constructor above creates a copy of the input string), on the other hand the move constructor steals the content of the input parameter.
class Student {
public:
std::string name;
// Copy constructor
Student(std::string const& name)
: name(name)
{}
// Move constructor
Student(std::string&& name)
: name(std::forward<std::string>(name))
{}
};