Is MyClass
in a valid state if it doesn't have a valid reference to an Entity
? If it is, then you should use a pointer. The constructor initializes the pointer to nullptr
, and the InitEntity
function assigns it to the address of a valid Entity
object.
class MyClass
{
public:
MyClass(): _entity(nullptr) {}
void InitEntity() { _entity = &Create(123); }
void doSomethingWithEntity()
{
if (_entity) ...
}
private:
Entity *_entity;
};
If MyClass
isn't in a valid state without a valid reference to an Entity
, then you can use a std::reference_wrapper<Entity>
and initialize it in the constructor.
class MyClass
{
public:
MyClass(): _entity(Create(123)) {}
void doSomethingWithEntity()
{
...
}
private:
std::reference_wrapper<Entity> _entity;
};
Of course which one you go with depends on how MyClass
is supposed to be used. Personally, the interface for std::reference_wrapper
is a little awkward for me, so I'd use a pointer in the second case as well (while still ensuring that it's always not null).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…