mercredi 23 septembre 2015

Preventing unsafe dereferencing of std::unique_ptr

Taken from a slide at cppcon2015:

unique_ptr<A> f() {
   auto a = make_unique<A>();
   return a;
}

//Why does this even compile?
const A & dangling = *f(); 

//BOOM!!!
use(dangling);

My question is: with rvalue references for *this, can this be solved?

I see in the spec in cppreference:

typename std::add_lvalue_reference<T>::type operator*() const;

Question:

  1. Would it make sense to disallow operator* for rvalue unique_ptrs and only have dereference valid for lvalue unique_ptrs?
  2. There are still valid use cases to keep the rvalue unique_ptr dereferenceable?

Like this:

//Make sure it is an lvalue.
typename std::add_lvalue_reference<T>::type operator*() const &;

NOTE: I am not sure of the syntax or correctness, I have no experience with rvalue references for *this.

Aucun commentaire:

Enregistrer un commentaire