Reputation: 25663
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?
Upvotes: 1
Views: 1304
Reputation: 173034
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 (i.e. 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.
Upvotes: 3