4 ms·
I have a C++ question. In the article, the author writes the Person constructor this way: Person(std::string first_name, std::string last_name) : first_n
by criddell 10y ago
I have a C++ question. In the article, the author writes the Person constructor this way:
Person(std::string first_name, std::string last_name)
: first_name(std::move(first_name))
, last_name(std::move(last_name))
{}
For string parameters, do you need to use std::move()? Won't the compiler do that anyway?
And does anybody really put the comma separating initializers at the start of the line? Yuck.
- kchoudhu 10y agoI do. Easier to comment things out when necessary. Hangover from SQL as well.
- flukus 10y agoI wish trailing commas were more widely supported in programming languages.
- GrayShade 10y agoIt's the same. You can comment out the last line easier, but not the first one. With trailing commas, it's the other way around.
- masklinn 10y ago> With trailing commas, it's the other way around. If the language supports trailing commas[0] (rather than just interspersed ones) that's not an issue as you could write: Person(std::string first_name, std::string last_name): first_name(std::move(first_name)), last_name(std::move(last_name)), {} [0] as Python, Ruby, Javascript or Rust do
- tomjakubowski 10y ago> And does anybody really put the comma separating initializers at the start of the line? Yuck. I don't, but I can see why someone would. When you copy-paste initializer lines around (say, because you've re-ordered members in the declaration), a leftover trailing comma often leads to insanely painful compiler errors. Organizing the commas this way makes that less likely.
- deleted 10y ago[deleted]
- Noughmad 10y agoNo, you should almost never use std::move. Instead, the parameters should be "const std::string&". This way, you avoid all the unnecessary copies and moves.
- silent_hunter 10y ago"const string&" - will always make a copy of the string for first_name and last_name, if we write "Person(std::string first_name, std::string last_name) : first_name(first_name) , last_name(last_name) {}" in case passed arguments are lvalues they will be copied, otherwise moved.