First:
array
doesn't explicitly declare a constructor. In particular, it doesn't have a constructor that takes a initializer list.
I think a clean way is to avoid the explicit new
in the code and leave it to standard functions:
package_t p = {header, body};
write(std::make_shared<package_t>(p));
The code would have looked even better if there was neither new
nor std::shared_ptr
:
package_t p = {header, body};
write(p);
Second, on Cppreference.com it reads:
Moreover, f(shared_ptr(new int(42)), g()) can lead to memory leak if g throws an exception. This problem doesn't exist if make_shared is used.
The standard doesn't specify an order for evaluating function arguments and expressions can be evaluated in any order as long as they produce the same result.
In
f(shared_ptr(new int(42)), g())
new int(42)
has to precede shared_ptr()
but not g()
and this can cause a leak if g
throws.
In
f(make_shared<int>(42), g())
the allocation happens inside make_shared
. If g
is called before make_shared
and if it throws, the memory would never get allocated.
If make_shared
is called before g
and if g
throws, the shared_ptr
object would have been created already and it's destruction is guaranteed because of RAII