user14056942
user14056942

Reputation:

Moving By Reference for strings?

In my class I wrote the following line:

string t1,t2;
MyClass(std::string tmp1, std::string tmp2) : t1(from), t2(to) {}

To improve performance I could change it to:

string t1,t2;
MyClass(const std::string &tmp1, const std::string &tmp2) : t1(from), t2(to) {}

But in that case won't the original arguments the the class members share the same string? (Both point at same object)?

Upvotes: 1

Views: 180

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

Let's start from the end:

But in that case won't the original arguments the the class members share the same string? (Both point at same object)?

Each of your strings is a separate value. Nothing is being shared between them, regardless where you initialize them from. If you initialize a string from a const&, a copy of the data is still being made.

To improve performance I could change it to:

You could, but that would have very slim chance of improving anything at all. You might be skipping one constructor call, but realistically that's gonna be optimized away anyway.

The common, idiomatic way to write such code is to capture by-value, and move out of said value if you need to store the value for later; otherwise take by const-ref.

MyClass(std::string t1, std::string t2) : t1(std::move(t1)), t2(std::move(t2)) {}

Upvotes: 9

Related Questions