vendredi 28 août 2015

What's the reasoning behind std::unique_ptr

As std::unique_ptr provides a handy way to avoid memory leaks and ensure exception safety, it is sensible to pass them around rather than raw pointers. Thus, one may want (member) functions with a signature like

std::unique_ptr<some_type> foo(some data);

Unfortunately, when implementing such a function, one cannot simply

std::unique_ptr<some_type> foo(some data)
{
  return { new some_type(data) };                  // error
}

but must instead

std::unique_ptr<some_type> foo(some data)
{
  return std::move( std::unique_ptr<some_type>( new some_type(data) ) );   // awkward
}

because the constructor unique_ptr::unique_ptr(pointer) is explicit. What is the reasoning behind this constructor being explicit?

One motivation to make constructors explicit is to guard against unintended implicit type conversion. However, as unique_ptr cannot be passed by value, this should not really be a problem, shouldn't it?

Aucun commentaire:

Enregistrer un commentaire