1

For learning purpose I was doing following exercise.

#include <iostream>

class DEMO
{
  public:
  DEMO(const DEMO& d)
  {
    std::cout << ">> [COPIED]" << std::endl;
    data = d.data;
  }

  DEMO(DEMO&& d)
  {
    std::cout << ">> [MOVED]" << std::endl;
    data = d.data;
  }

  DEMO(int i)
  {
    std::cout << ">> [DEFAULT]" << std::endl;
    data = i;
  }

  DEMO& operator=(const DEMO& d)
  {
      if(this != &d)
      {
        std::cout << ">> [ASSIGNED]" << std::endl;
        data = d.data;
      }
      return *this;
  }

  int data;
};

DEMO&& d1()
{
  return DEMO(44);
}

const DEMO& d2()
{
  return DEMO(66);
}

DEMO d3()
{
  return DEMO(55);
}


int main() 
{
  std::cout << "CASE 1" << std::endl;
  DEMO a1 = d1();

  std::cout << "CASE 2" << std::endl;
  DEMO a2 = d2();

  std::cout << "CASE 3" << std::endl;
  DEMO a3 = d3();

  std::cout << "CASE 4" << std::endl;
  DEMO a4(33);

  std::cout << "CASE 5" << std::endl;
  DEMO a5 = a4;  

  std::cout << "CASE 6" << std::endl;
  DEMO a6 = std::move(a4);  

  return 0;
}

OUTPUT

CASE 1
>> [DEFAULT]
>> [MOVED]
CASE 2
>> [DEFAULT]
>> [COPIED]
CASE 3
>> [DEFAULT]
CASE 4
>> [DEFAULT]
CASE 5
>> [COPIED]
CASE 6
>> [MOVED]

I don't understand what happened at case 3. Only one default constructor call ? I was expecting either copy or move constructor call. Can anyone explain what happened here.

Object a3 get proper value 55 from d3(). So it seems it copied properly.

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
Jai
  • 1,292
  • 4
  • 21
  • 41

0 Answers0