Xavier
Xavier

Reputation: 9049

How should a local variable in a function be initialized?

How should a local variable in a function be initialized? For performance reasons should I do it like this?

Point2D point(1,2);

or like this?

Point2D point = Point2D(1,2);

Does it even matter?

Upvotes: 1

Views: 143

Answers (5)

David Grayson
David Grayson

Reputation: 87386

You should do it the first way because if you do it the second way I believe the compiler does something more complicated than necessary. I think it creates a temporary object to represent the right-hand side, then uses the copy constructor to copy values to the object on the left hand side.

I might be wrong about this, so check your assembly listing.

Upvotes: 4

Michael Price
Michael Price

Reputation: 8968

Most of the time return-value optimization will make those two options similar enough from a performance perspective (especially if you have a move-assignment operator defined)

There are other things to consider though.

If your type has an empty constructor, doing this is problematic:

Point2D p(); // instead of Point p;

This is known as the Most Vexing Parse. It can be avoided by using the second form:

Point2D p = Point2D();

Or by using the uniform initialization syntax introduced in the latest standard:

Point2D p{};

Upvotes: 2

Paul Manta
Paul Manta

Reputation: 31567

Yes, it does matter. The first version, Point2D point(1,2) will call the constructor, while the second, Point2D point = Point2D(1,2) will first create a new Point2D (the one to the right) and then will call the copy constructor to actually create point. As you can see, this is a big difference between C++ and Java or C#.

Upvotes: 2

Morten Kristensen
Morten Kristensen

Reputation: 7613

The first one only calls the constructor while the second first calls the constructor and then copies it to point. Thus you should use the first one because it doesn't initiate a copy operation.

Upvotes: 2

Björn Pollex
Björn Pollex

Reputation: 76778

No, it does not matter. Both will result in a call to the same constructor.

Upvotes: 7

Related Questions