Re: Resetable mixin / idiom
On 17 juil, 03:50, pt <gall.c...@gmail.com> wrote:
On 16 Lip, 19:21, Dragan Milenkovic <dra...@plusplus.rs> wrote:
pt wrote:
template<typename T, typename... A>
void reset(T & t, A && ... a) {
t.~T();
new (&t) T(forward<A>(a)...);
}
The very first thing that comes to my mind is exception safety
(unless you require a no-throw constructor). There are a few
solutions to this problem.
Can you please explain the solution to the exception problem?
template<typename T, typename... A>
void reset(T& t, A&&... a)
{
t = T(forward<A>(a)...);
}
which is simple and just works for all types,
or
template<typename T, typename... A>
void reset(T& t, A&&... a)
{
T tmp(forward<A>(a)...);
swap(t, tmp);
}
which does nothing more than invoking your typical operator=
implementation directly,
or
template<typename T, typename... A>
void reset(T& t, A&&... a)
{
T old(move(t));
t->~T();
try
{
new(&t) T(forward<A>(a)...);
}
catch(...)
{
try
{
new(&t) T(move(old));
}
catch(...)
{
terminate();
}
throw;
}
}
which saves the old value, destructs, and then restores it on failure
to construct the new value. (requires nothrow move constructor)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]