Imagine I have a Device class. I don’t want the programmer to be able to instantiate his own Device objects so now I create a DeviceManager class. The DeviceManager is the only entity that will be instantiated and gives the programmer access to Device objects by having the programmer specify an ID of some sort. This way, only the DeviceManager class needs to be cleaned up by the programmer and no stray Device objects are left behind. My main concern is how to control access to objects in the interest of studious garbage collection. Is a “manager” pattern like I’ve described a good idea in C++? Thanks!
Share
If you really need it, yes.
To achieve this control, you can make the constructor of the
Deviceprivateand declareDeviceManageras protected in theDeviceclass.You could also return a smart pointer to a
Device(recommended) and keep created devices inside theDeviceManager, depending on what you need.This is called the instance manager pattern. The
DeviceManageris also a factory of devices.Also, C++ doesn’t have garbage collection, but if you use a smart pointer you needn’t worry about memory management.