Home > Enterprise >  What special member function is used for copy initialization in c ?
What special member function is used for copy initialization in c ?

Time:01-03

I'm testing c class initialization.

class Point
{
private:
    int x,y;
public:
    Point() = delete;
    Point(int a):x(a), y(0) { std::cout << "Conversion" << std::endl;}
    
    Point(const Point&) { std::cout << "Copy constructor" << std::endl;}
    //Point(const Point&) = delete;
    Point& operator=(const Point&) = delete;

    Point(Point&&) = delete;
    Point& operator=(Point&&) = delete;
};

int main()
{
    Point p1(5); //case1
    Point p2 = 5; //case2

    return 0;
}

In the above code, I thought "5" will be converted to a temp object by conversion constructor for both case1/2 at first. And then, I expected that copy constructor must be used for initializing of p1 & p2. But, it was not. When I run this code, I saw just two "Conversion" message in console. No "Copy Constructor" message.

Even though, I deleted all copy constructor, move constructor, copy assignment operator and move assignment operator, this code worked well.

I would appreciate if you let me know what special member function will be used for initializing after creating temp object for "5",

I am using g compiler with std=c 17 option.

CodePudding user response:

Case I

In case 1 the converting constructor is used since you have provided a constructor that can convert an int to Point. This is why this constructor is called converting constructor.

Case II

From mandatory copy elison

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type.

In case 2, even if you delete copy/move constructor only the converting constructor will be used. This is due to mandatory copy elison(in C 17) as quoted above.

  • Related