I see that you have already accepted the answer, but I would like to expand the answers.
As deepmax said, if you walk by value, you can write your constructor to take advantage of the "movement semantics." This means that instead of copying data, it can move from one variable to another.
It is written as follows:
class Name{ public: Name(std::string var): mem_var(std::move(var)){} std::string mem_var; };
Which seems like a good idea, but actually no more efficient than copy constructor
class Name{ public: Name(const std::string &var): mem_var(var){} std::string mem_var; };
The reason for this is that in general it looks like this:
auto main() -> int{ Name name("Sample Text"); }
only one copy will be made in any case (see copy elision ), and in another case
auto main() -> int{ std::string myname = "Hugh Jaynus"; Name name(myname); }
2 copies will be made in the "effective" way of semantics of moving by value!
This is a good example of when to use the copy constructor (or pass-by-reference) should , rather than an example against it.
On the contrary ...
If you write an explicit constructor that uses move semantics, you can get an effective solution regardless of the circumstances.
This is how I wrote out the class definition:
class Name{ public: Name(const std::string &first_, const std::string &last_) : first(first_), last(last_){} Name(std::string &&first_, std::string &&last_)
Then, when you use this class, you can decide when it is more efficient.
If we return to our examples, we can rewrite them to use the best or most efficient constructor:
auto main() -> int{ // pass by reference best here Name myname("Yolo", "Swaggins"); // move most efficient here // but never use 'first' and 'last' again or UB! std::string first = "Hugh", last = "Jaynus"; Name yourname(std::move(first), std::move(last)); }
Never take for granted that one solution is better than everyone else!