Reputation: 57
I have a user defined class Fixed, with a default constructor, a parameter constructor and an assignment operator.
When I declare an object and then assign it:
Fixed a;
a = Fixed( param );
I get:
Of course I could (and should) prefer initialization (Fixed a(param)
) over assignment.
Yet I'm trying to understand what happens on line 2.
Is a temporary object created ?
Here is what i found about temporary object.
In some cases, it is necessary for the compiler to create temporary objects. These temporary objects can be created for the following reasons: ...
To store the return value of a function that returns a user-defined type. These temporaries are created only if your program does not copy the return value to an object.
Here, the program does copy the return value of the object, so how come a temporary object is created ?
Upvotes: 0
Views: 478
Reputation: 11968
To store the return value of a function that returns a user-defined type. These temporaries are created only if your program does not copy the return value to an object.
The line you mention is irrelevant. Fixed(param)
is not a function call.
The line refers to something like:
Fixed f(param) {
return Fixed(param);
}
...
Fixed a;
a = f(param);
In this case the line explains that you shouldn't get a temporary created to hold the result of f
and then copy that to a
. This would be in addition to what you've seen above.
Also experiment with optimization levels.
Upvotes: 4
Reputation: 409166
Is a temporary object created ?
Yes.
The expression Fixed( param )
will create a temporary object. This temporary object will then be passed to the assignment operator of the a
object.
The statement
a = Fixed( param );
is somewhat equivalent to
{
Fixed temporary_object( param );
a.operator=( temporary_object );
}
Upvotes: 6