mercredi 6 juin 2018

Reference for rvalue or not

I wonder will next code work correct with v and v2 variable or these are references for temporary variables? In other words, can I capture returned rvalue by reference? I think no, but my teamlead think another way.

#include <iostream>

struct Foo {
  Foo(Foo&&) = delete;
  Foo& operator=(Foo&&) = delete;

  Foo() {
    std::cout << "Constructor" <<std::endl;
  }
  Foo(const Foo&) {
    std::cout << "Copy Constructor" <<std::endl;
  }
  Foo& operator=(const Foo&) {
    std::cout << "Copy  = Constructor" <<std::endl;
    return *this;
  }
  ~Foo() {
    std::cout << "Destructor" <<std::endl;
  }
};

Foo foo() {
  Foo v;
  return v;
}

int main() {
  const auto& v = foo();
  const auto& v2 = v;
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire