Default move constructor is generated even when copy ctor is defined by user in cpp

Viewed 23

I see a strange behaviour while running the below sample code.

#include <iostream>

class foo {
private:
    int m_data;
public:
    foo (int i) : m_data(i) {
        std::cout << "Ctor default. Data is: " << m_data << std::endl;
    }

    foo(const foo& rhs) {
        m_data = rhs.m_data;
        std::cout << "COPY ctor invoked" << std::endl;
    }

    ~foo() {
        std::cout << "Dtor default" << std::endl;
    }
};

void bar (foo obj) {
    std::cout << "Do nothing" << std::endl;
}

int main() {
    //foo foo1(1);
    //bar(foo1);
    bar(foo(10));  /* the call foo(10) clearly is a RValue */
    return 0;
}

Since i have explicitly defined a copy constructor for the class foo I believe the compiler should not generate the default move constructor for the same. But running the above code shows a violation of this rule. It is not invoking the copy ctor instead the compiler generated move ctor is being used.

Appreciate if someone can help to understand this behaviour.

0 Answers
Related