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)?

josecgon
  • 35
  • 5
  • 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. – Sam Varshavchik Jul 14 '22 at 13:46
  • 6
    write code to be explicit, if you want it to be moved use `std::move` – 463035818_is_not_an_ai Jul 14 '22 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. – pptaszni Jul 14 '22 at 14:04
  • [Dupe1](https://stackoverflow.com/questions/23929800/is-stdmove-really-needed-on-initialization-list-of-constructor-for-heavy-membe), [Dupe2](https://stackoverflow.com/questions/51705967/advantages-of-pass-by-value-and-stdmove-over-pass-by-reference) – Jason Jul 14 '22 at 14:08

0 Answers0