Consider we have a class Foo
where we have a default and copy constructor what is the difference between creating object like Foo f1
and Foo f1 = Foo()
, in my test both of them call the default constructor , does they reserved in different memory location as the one created with pointer
Before C++17, in Foo f1 = Foo();
the compiler was allowed to create a temporary Foo
instance, then move it into f1
(look up "move semantics").
Since C++17, the compiler isn't allowed to create a temporary ("mandatory copy elision"), so the two are almost completely equivalent.
The difference is that for some types, Foo f1;
will leave the object uninitialized, while Foo f1 = Foo();
will zero it (just like Foo f1{};
or Foo f1 = Foo{};
). This applies to all non-class types, and to those classes that either don't have a custom ("user-declared") default constructor, or have it marked =default
inside of the class body; for those classes the fields that would otherwise remain uninitialized are zeroed.
does they reserved in different memory location
No, f1
ends up in the same location regardless.
as the one created with pointer
No, there are no pointers there.