In C++11, you can use a shared_ptr<>
to establish an ownership relation with an object or variable and weak_ptr<>
to safely reference that object in a non-owned way.
You can also use unique_ptr<>
to establish an ownership relation with an object or variable. But what if other, non-owning objects want to also reference that object? weak_ptr<>
isn't helpful in this case. Raw pointers are helpful but bring various downsides (e.g. they can be automatically initialized to nullptr but this is accomplished through techniques that are not consistent with the std::*_ptr<>
types).
What is the equivalent of weak_ptr<>
for non-owning references to objects owned via unique_ptr<>
?
Here's a clarifying example that resembles something in a game I'm working on.
class World
{
public:
Trebuchet* trebuchet() const { return m_trebuchet.get(); }
private:
std::unique_ptr< Trebuchet > m_trebuchet;
};
class Victim
{
public:
Victim( Trebuchet* theTrebuchet ) : m_trebuchet( theTrebuchet ) {}
~Victim()
{
delete m_trebuchet; // Duh. Oops. Dumb error. Nice if the compiler helped prevent this.
}
private:
Trebuchet* m_trebuchet; // Non-owning.
};
shared_ptr< Victim > createVictim( World& world )
{
return make_shared< Victim >( world.trebuchet() );
}
Here we use a raw pointer to maintain a non-owning relationship with an object owned via unique_ptr<>
elsewhere. But is raw the best we can do?
The hope is a type of pointer that:
- Looks like the other modern pointer types. E.g.
std::raw_ptr<T>
.
- Replaces raw pointers so that a codebase that uses modern pointer types throughout can find all pointers via a search for
_ptr<
(roughly).
- Auto-initializes to nullptr.
Thus:
int* p; // Unknown value.
std::raw_ptr< int > p; // null.
Does this type already exist in C++ now, is it proposed for the future, or is another implementation broadly available in e.g. Boost?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…