Reputation:
In this code :
class iop {
public:
iop(int y) {
printf("OK\n");
}
iop() {
printf("NO\n");
}
};
int main()
{
line 1- iop o;
line 2- o = 8;
line 3- return 0;
}
My conclusion of the way this C++ code work with is:
Create an object of iop
class (o
) using the default parameterless constructor.
Create an rvalue object of iop
class using the constructor with parameter (int) and using the overloaded operator (operator = (iop&&)) to assign it to the object (o
) then call the destructor of that rvalue.
Call the destructor of the object (o
).
Is my conclusion correct?
Edit This code also compiled
class iop {
public:
iop(int y) {
printf("OK\n");
}
iop() {
printf("NO\n");
}
};
int main()
{
iop o(5);
o = 8;
return 0;
}
output :
OK
OK
That is mean two object are created (o) and one is temporary and the operator= assigen (o) with the temporary object that its constractor argument is 8
Upvotes: 2
Views: 234
Reputation: 75668
The class iop
has implicitly defined copy and move constructors and assignments.
o = 8;
This will attempt to call operator=
. As I've stated the copy and move assignment operators are implicitly defined:
iop& operator=(const iop&);
iop& operator=(iop&&);
Because iop
is implicitly constructible from int
, both operators are viable, but the move one is preferred as is a perfect match.
So yes, a temporary is created from 8
, that is moved into o
. At the end of the full expression (at ;
) that temporary is destroyed. At the end of main
scope o
is destroyed.
So your code is more or less equivalent to o = iop{8}
.
Sidenote: if you make the int constructor explicit i.e. explicit iop(int y)
then o = 8;
will no longer compile.
Upvotes: 4