"Karl Heinz Buchegger" <kb******@gasca d.at> wrote...
Victor Bazarov wrote:
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote...
tz***@phonedo.c om wrote:
>
> Call constructor on an already existing instance?
> I like to execute the constructor logic,
> including all the class member constructors,
> on an existing instance (with out executing the destructor).
> Can it be?
Lookup 'placement new' in your favorite text book.
According to language rules the number of calls to constructors
is supposed to match the number of calls to destructors. So,
what the OP wants would violate that. Whatever logic needs to
be executed should be put in a separate function.
Thanks for pointing out.
Just for interest: Does the standard really have such a rule?
(Meaning: could you guide me to where to find it?)
If you look at 3.8 Object Lifetime, you'd notice that in the example
on the page 50 (after paragraph 7) the technique with constructing
an object "on top of" or "in place of" another one is given _almost_
like the one you hinted at. However, a destructor is called first.
The requirement is that the storage can be reused if the lifetime of
the object that occupies that storage has ended. Another definition
is that the lifetime starts when constructor returns and ends when
the destructor is called. That suggests that to have a proper C++
program every object has to have clean lifetime: c-tor through d-tor.
There is, however, a diviation from that requirement, see 3.8/4.
The Standard says that the program may end the lifetime by reusing
the storage and that it's not required to call a destructor, but
undefined behaviour may occur if it doesn't.
Victor