I want to fill the back buffer while the hot buffer is being read, and want the hot buffer to be un-writable and const
for this reason,
So you decided to change your implementation to enforce your desired interface. Often, this is a sub-optimal approach.
Better would be to encapsulate more. I would re-imagine these variables as a class, where internally both buffers are writable, but external code sees the hot buffer as const
. (If these variables are already inside a class, re-imagine them as a nested class.) This would be a small class with a single, focused purpose – controlling which region of memory is considered "hot" and which is "back". For example:
// Not sold on the name, but it will do for this demonstration
class BufferManager {
public:
// Instead of access to the smart pointers, provide direct access to the buffers.
// (Hide the detail of where these buffers live.)
const Buffer & hotBuffer() const { return *hot; }
Buffer & backBuffer() { return *back; }
// A way for external code to say it is time to swap buffers:
void flip() { hot.swap(back); }
// Placeholder constructor; modify to suit your needs:
BufferManager() : hot(std::make_unique<Buffer>()),
back(std::make_unique<Buffer>())
{}
private:
std::unique_ptr<Buffer> hot;
std::unique_ptr<Buffer> back;
};
With this approach, both smart pointers point to something modifiable, so there is no longer a problem swapping them. Anything outside this class, though, sees the hot buffer as const
.
You might want to play with the names a bit. (Since you'll need a name for the BufferManager
variable, it might be enough to name the accessor functions hot
and back
, which of course means renaming the private data members.) The interface might need refining. The main point is that you add a layer of abstraction so that the interface applies const
when appropriate, not the implementation.
Note: It might be appropriate to incorporate the code that fills the back buffer into this class. Perhaps both the back buffer and flip()
could be made private. A key thing to keep in mind is that nothing in this class should be interested in reading the hot buffer. That is for outside code to deal with. If this is done, the purpose of this class morphs into providing the hot buffer.