Puzzle #5 (based on C++17)

#include <iostream>

struct Foo
{
  Foo() = default;
  Foo(const Foo&) { std::cout << 1; }
  Foo(Foo&&) { std::cout << 2; }
  Foo& operator=(const Foo&) { std::cout << 3; return *this; }
  Foo& operator=(Foo&&) { std::cout << 4; return *this; }
};

int main()
{
  const Foo foo;
  Foo bar = std::move(foo);
}

With given code and C++17 compiler, pick one answer:

  • Guaranteed to print 1.
  • Guaranteed to print 2.
  • Guaranteed to print 3.
  • Guaranteed to print 4.
  • Undefined behavior.
  • Implementation defined.
  • Will not compile.
Click here for the answer

The correct answer is: Guaranteed to print 1.

Explanation is rather simple. std::move will return const rvalue reference, which compiler won’t be able to cast to non-const move reference, which move ctor accepts. The only thing that it can do is to cast it to const ref, thus copy ctor is selected.

Thanks for reading o/