Reputation: 43
Let's assume we have interface selector_interface_t
and implementation of this interface pin_selector_t
.
class selector_interface_t
{
public:
virtual void select(uint8_t address) = 0;
virtual void deselect() = 0;
};
class pin_selector_t : public selector_interface_t
{
private:
uint8_t mask;
public:
pin_selector_t(uint8_t mask);
void select(uint8_t address);
void deselect();
};
And now we want to pass object witch implements this interface to class myclass_t
and store for future use by other myclass_t
methods (eg. strobe
).
class myclass_t
{
private:
selector_interface_t * selector;
public:
myclass_t(selector_interface_t & selector);
void strobe(uint8_t pin);
};
myclass_t::myclass_t(selector_interface_t & selector) // : selector(selector)
{
// ...
}
void myclass_t::strobe(uint8_t pin)
{
this->selector->select(pin);
this->selector->deselect();
}
The only way is pass implementation by pointer or by reference. I prefer second solution and pass by reference. But I cannot simply store this reference in myclass_t
object because of lifetime of object with interface implementation. It would be better to make a copy. But I cannot have selector_interface_t
field member. I can only have reference or pointer to this type. On the other way I'd like to avoid using malloc. What can I do with it?
Upvotes: 1
Views: 719
Reputation: 18972
If you can't guarantee that the implementation has the right lifetime, then you need to manage it, which means dynamically allocating it. (Using new
, not malloc
.)
I would strongly suggest using either shared_ptr<selector_interface_t>
or unique_ptr<selector_interface_t>
- depending on whether or not you ever want to share implementation objects between clients. You then get correct code with very little effort.
Upvotes: 1
Reputation: 552
If you are the one who creates the selector_interface_t type then you can store it inside a shared_ptr and have the myclass_t class hold a weak_ptr or shared_ptr to the interface.
If you are not the one who creates selector_interface_t then I assume you have other means of keeping the object alive, wrap it in a class that manages the lifetime and that object wrap in shared_ptr.
Upvotes: 2