简体   繁体   中英

object construction with assignment operator

I am wondering that object construction with assignment operator works, never seen that before I saw this question:

return by value calls copy ctor instead of move

Reduced example code:

class A
{
    public:
        int x;
        A(int _x):x(_x){ std::cout << "Init" << std::endl;}
        void Print() { std::cout << x << std::endl; }
        A& operator = ( const int ) = delete;
};

int main()
{
    A a=9;
    a.Print();
}

Is writing of

A a(9);
A a{9};
A a=9;

all the same?

This has nothing to do with assignment operator, it's initialization, more precisely copy initialization , which just uses the equals sign in the initializer.

when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initializer consisting of an equals sign followed by an expression.

For A a = 9; the approriate constructor (ie A::A(int) ) will be invoked to construct a . 1

A a(9); is direct initialization , A a{9}; is direct list initialization (since C++11), they all cause the A::A(int) to be invoked to construct the object for this case. 2


1 Before C++17 the appropriate move/copy constructor is still required conceptually. Even though it might be optimized out but still has to be accessible. Since C++17 this is not required again.

2 Note that there're still subtle differences among these initialization styles, they may lead to different effects in some specialized cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM