0
struct custom
{
  custom();
  custom(const custom &);
  custom(custom &&);
};

custom find()
{
  return custom();
}

void take(const custom &c)
{
  custom temp = t;
}

void take(custom &&c)
{
  custom temp = std::move(c);
}

How many calls to the constructors of custom are made and in what order by the following:

custom first = find();
take(first);

custom second = find();
take(std::move(second));

The first find() call just uses the default constructor. The first take call uses the copy constructor I believe. Second find() call also just uses the default constructor. I am not certain of the second take call. I believe it uses the move constructor here. Is that correct? If so, the sequence of constructor calls is default, copy, default, move (in this order)?

user5965026
  • 465
  • 5
  • 16
  • 3
    You could simply add logging in the constructors and then you would see the sequences for yourself. [Demo](https://ideone.com/a19kOr) – Remy Lebeau Sep 02 '21 at 02:14
  • @RemyLebeau I did and it seems to confirm what I wrote in the OP, but I am a bit confused now why, e.g., the first `find()` call does not invoke the move constructor. The res of the first `find()` call is an r-value, so shouldn't it get moved into the variable `first`? – user5965026 Sep 02 '21 at 02:17
  • "*the first find() call does not invoke the move constructor"* - correct, because nothing is being moved. "*The res of the first find() call is an r-value, so shouldn't it get moved into the variable first?*" - no. Read up on ["Copy Elison"](https://en.cppreference.com/w/cpp/language/copy_elision) (also known as "Return Value Optimization"). – Remy Lebeau Sep 02 '21 at 02:22
  • 1
    Have a look here: [What are copy elision and return value optimization?](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – Fabio says Reinstate Monica Sep 02 '21 at 02:24
  • @RemyLebeau I have read that before but my impression of that is it's platform dependent? Are you saying in this case the move will never be called and copy elison will always be done? – user5965026 Sep 02 '21 at 02:24
  • 1
    @user5965026 "*I have read that before but my impression of that is it's platform dependent?*" - once upon a time, but not anymore, it is now required standard behavior since C++17. "*Are you saying in this case the move will never be called and copy elison will always be done?*" - in modern C++, yes. The standard guarantees it. – Remy Lebeau Sep 02 '21 at 02:27
  • @user5965026 Note that there is a difference in asking "What are the various constructor calls in this code?" and "How many calls to the constructors of custom are made". You have 3 different user-defined constructors -- default, copy, and move constructor. That is a given, That is totally different than asking "what gets called when". – PaulMcKenzie Sep 02 '21 at 02:36

0 Answers0