class Entity
{
};
//Entity e(); This was a mistake
Entity e;
Entity e1 = Entity();
The second method looks like an anonymous object is created which in turn initializes e1,but i dont think that is what's happening.
class Entity
{
};
//Entity e(); This was a mistake
Entity e;
Entity e1 = Entity();
The second method looks like an anonymous object is created which in turn initializes e1,but i dont think that is what's happening.
Entity e1 = Entity();
You're right about this one. A temporary, default-constructed Entity
is created, then used to copy-initialise e1
.
Despite appearances, that no longer creates a temporary, it only looks like it does. The semantics of the line are now that there is simply a declaration of an Entity
called e1
, initialised with no constructor arguments. The temporary isn't "optimised out": it no longer ever exists in the first place.
This may seem like a pedantic distinction, and in such a simple case it kind of is. But this so-called "mandatory elision" is a fundamental change to how temporaries are defined in the language, and does have broader ramifications elsewhere that are worth making yourself aware of if you start working on larger and more complex projects.
Entity e();
This declares a function called e
to return an Entity
.
Yes, even if you put it in block scope.
Just declare an Entity
Entity e;
In case Entity
does not have a user-defined default constructor (and the members don't have default values), then Entity e
and Entity e1 = Entity();
have different results.
struct Entity
{
int x;
};
int main() {
Entity e;
Entity e1 = Entity();
std::cout << e.x << std::endl; // access to uninitialized member variable
std::cout << e1.x << std::endl; // access to zero initialized member variable
}
Whether that is relevant or not depends on the class you use, and how you will use it.
If you use e.g. an std::array
and you want the elements to be zero-initialized, you need to write std::array<int,5> a = std::array<int,5>()
or std::array<int,5> a{}
.
This is one of the reasons why AAA (almost always auto), is suggested (e.g. auto a = std::array<int,5>()
) by some people like Herb Sutter.