Say I have this class:
class MyClass
{
public:
MyClass(std::string str) : m_str(std::move(str)) {}
private:
std::string m_str;
}
In modern C++, will this under any circumstance be less efficient than passing the string by const reference? I.e. if I have parameters that support move and the parameters are only copied to members and not otherwise used in the constructor can I always write code this way to get optimal performance?
The way I see it:
- If the compiler does not do copy elision there is a copy, but that copy would have been needed anyway for a const reference (only in that case it would have been in the constructor rather than before calling the constructor).
- If the compiler manages to utilize copy elision when passing the string to the constructor this solution should be a net benefit from using a const reference because there is now no copies what so ever.