K
Keith H Duggar
* Helge Kruse, on 21.06.2010 16:15:
No, there is no copy constructor call involved.
It has /the same effect/ as creating a temporary TestStructure,
value-initializing that structure, and calling the copy assignment operator.
For a POD value-initialization reduces to zero-initialization.
Whether an actual assignment (copying) is performed is a quality of
implementation issue; a good compiler may just call memset, but with the
difference that the source code is now safe.
Whether stack space is used is a quality of implementation issue.
Two other alernatives are
swap(myTest,TestStructure()) ;
myTest = move(TestStructure()) ; //C++0x
where the "swap trick" can be very useful for containers etc.
That's both inefficient and needlessly unconventional <g>.
A constructor deals with raw, uninitialized memory, e.g. nothing needs to be
deallocated. Assignment deals with initialized stuff, where e.g. something may
need to be deallocated. An Initialize method that could be called later would
likewise have to deal with and have as basic assumption, initialized stuff.
And that means (1) inefficiency of construction, because the constructor would
first have to default initialize and then call Initialize, and (2) that
Initialize plays the role of a special-cased copy assignment operator.
So why not use the copy assignment operator for assignment (that's what it's /for/)?
And for construction you really don't want to get into the habit of expressing
construction in terms of assignment, if you can help it. It yields extreme
redundance, subtleties of multiple initializations where bugs will creep in (not
to mention inefficiency), and is generally not exception safe. The conventional
way is instead to express assignment in terms of construction.
+1
Please consider taking Alf's advice above. C++ has constructors,
destructors, copy, swap, and move idioms. With that full toolset
there is almost never a need for "initialize" methods. Strongly
prefer some combination of those together with RAII/RRID rather
than whatever "initialize" pattern.
KHD