0

I am wondering what performance/code quality bearing differences come from the use of move semantics, or passing something by a const reference, and copying it into a field member. (For the use of initializing class members.)

Here's an example.

class Foo {
  public:
    Foo(const int& bar) : bar(bar) {}
    Foo(int bar) : bar(std::move(bar)) {}
    int getBar() const { return bar; }
  private:
    int bar;
};

class Bar {
  public:
    Bar(const Foo& foo) : foo(bar) {}
    Bar(Foo foo) : foo(std::move(foo)) {}
  private:
    Foo foo;
};

Would the const reference be a better option, or the constructor utilizing std::move. I am a little confused on which one to chose, although from static analysis(clang tidy), apparently I should be using std::move all the time.

  • If this is a class you are writing, implement both and let the callers decide what to do. (Note that for the `int` example, there is no point in using the reference constructor since the type is small. A reference could actually be larger, and adds indirection. `std::move` is also pointless here. The only constructor should be `Foo(int b) : bar{b} {}`) – cdhowie May 26 '20 at 06:22

0 Answers0