0

Having following code:

#include <iostream>
#include <vector>

using namespace std;

class CIntPtr {
public:
    int* ptr;
public:
    CIntPtr() {
        // Default constructor
        cout << "Calling Default constructor\n";
        ptr = new int;
    }

    CIntPtr(const CIntPtr& obj) {
        // Copy Constructor
        // copy of object is created
        this->ptr = new int;
        // Deep copying
        cout << "Calling Copy constructor\n";
    }

    CIntPtr(CIntPtr&& obj) {
        // Move constructor
        // It will simply shift the resources,
        // without creating a copy.
        cout << "Calling Move constructor\n";
        this->ptr = obj.ptr;
        obj.ptr = NULL;
    }

    ~CIntPtr() {
        // Destructor
        cout << "Calling Destructor\n";
        delete ptr;
    }

};

int main() {    
    CIntPtr bar = CIntPtr();   // move-construction 
    return 0;
}

There is only "normal" ctor called. Should't it be ALSO move ctor get called since there is a temp obj created in line: CIntPtr bar = CIntPtr()?

PS. Can someone provide/lists all the possible cases when move constructor is called?

Derek81
  • 145
  • 9
  • 1
    This might be a case of [copy elision](https://en.cppreference.com/w/cpp/language/copy_elision). [This video](https://www.youtube.com/watch?v=fSB57PiXpRw) illustrates this process. – emegona Aug 31 '20 at 20:24
  • 1
    [Documentation for Copy Initialization](https://en.cppreference.com/w/cpp/language/copy_initialization). There are a lot of options in [C++ initialization](https://en.cppreference.com/w/cpp/language/initialization), and until you are familiar with all of the twists and turns, [and there are many](https://www.youtube.com/watch?v=7DTlWPgX6zs), you're going to get surprise after surprise. – user4581301 Aug 31 '20 at 21:18

0 Answers0