1

Given this example:

#include <string> class Foo { public: Foo(std::string p_member) : m_member{p_member} {} private: std::string m_member; }; int main() { Foo f{"Test"}; return 0; } 

In Foo ctor, is the string copied or moved by default? Do I have to explicitly write the std::move(p_member)?

4
  • 2
    Pedantically, it is copied. If the C++ compiler can prove that there are no observable effects (I'd give it 50-50 odds), it can optimize it to a move. If you want to guarantee a move, yes, make it explicit. Commented Jul 14, 2022 at 13:46
  • 6
    write code to be explicit, if you want it to be moved use std::move Commented Jul 14, 2022 at 13:48
  • As a side note, be careful with this kind of micro-optimizations. If you write m_member{std::move(p_member)} and half a year later you/someone_else add more logic to the constructor, where you would like to reuse your p_member, you will run into not so obvious bug. Commented Jul 14, 2022 at 14:04
  • Dupe1, Dupe2 Commented Jul 14, 2022 at 14:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.