In my program I am drawing a block of text to screen and I want to be able to find the text that corresponds to a given pixel. In my architecture there are two classes, the text_view
and the draw_device
. draw_device
is an abstract base class which provides drawing functions as well as functions to calculate, in pixel terms, the size of a given block of text. text_view
is a class that stores information about where blocks and lines of text are on screen in order to speed up lookup and redraw operations.
Since text_view
stores pixel information, it is necessarily dependent on the choice of draw_device
. If a different draw_device
is used, it might render text somewhat differently and leave the text_view
storage in inconsistent state.
My question is, how best to represent this relationship?
I can let the user of the two classes deal with it, and pass in a draw_device
reference for each function called. They would need to always pass in the same type of draw_device
or evil will happen.
class text_view{
public:
void rearrange_text(const draw_device &);
int lookup_text(const draw_device &, int x, int y) const;
void draw_text(draw_device &) const;
};
I can keep a naked pointer in the text_view
to the draw_device
to simplify the function interfaces, at the cost of requiring the user of the classes deal with managing the lifetime issues
class text_view{
draw_device * device;
public:
void rearrange_text();
int lookup_text(int x, int y) const;
void draw_text() const;
void change_draw_device(draw_device *);
};
I can keep a shared_ptr
in the text_view
so the user won't have to worry about lifetime issues, at the cost of forcing them to use a shared_ptr
instead of stack allocating or a unique_ptr
etc.
I don't like the shared_ptr
solution as I don't think the text_view
should own the draw_device
. It is merely a user of it.