Should I write constructors using rvalues for std::string?

c++, c++11, constructor, rvalue-reference, string

Solution

X (std::string&& s) : S(s) { }

That is not a constructor taking an rvalue, but a constructor taking an rvalue-reference. You should not take rvalue-references in this case. Rather pass by value and then move into the member:

X (std::string s) : S(std::move(s)) { }

The rule of thumb is that if you need to copy, do it in the interface.

Problem

I have a simple class: ``` class X { std::string S; X (const std::string& s) : S(s) { } }; ``` I've read a bit about rvalues lately, and I've been wondering, if I should write constructor for `X` using rvalue, so I would be able do detect temporary objects of `std::string` type? I think it should look something like: ``` X (std::string&& s) : S(s) { } ``` As to my knowledge, implementation of std::string in compilers supporting C++11 should use it's move constructor when available.

Original source

Related problems