Let’s assume I have a singleton class:
class Singleton {
public:
static Singleton* getInstance();
void doit();
std::vector<Object*>& getVector();
private:
std::vector<Object*> _vector;
static Singleton *instance;
Singleton();
~Singleton();
Singleton(const Singleton&);
};
class Delegator {
public:
void main();
}
- In the
doitmethod I populate the_vectorwith pointers to objects. - In the
main()from theDelegatorclass, I callgetVector()and display the results.
Given this abstraction, I have the following questions:
- Can I delete all the pointers to instances of Object in the
main()fromDelegator(after displaying the results). If yes, is this recommended? - Does the singleton ever get destroyed? In other words, will the reference returned in
getVector()always be valid? - I return a reference to a vector instead of a copy of the vector in
getVector(). Given that the vector only contains pointers to objects and will not modify the vector content outside theSingletonclass, is there any efficiency gained from returning a reference?
Thank you in advance
My first answer to the question you didn’t ask is this:
Do not use Singleton. It’s an anti-pattern. It makes the code it touches worse. It kills testability and makes it harder to modify your program in the future.
This really excellent article talks in great detail about why Singleton is a bad idea.
To answer the questions you did ask…
Objects they point to. Additionally, if you return a copy and have themainfunction delete all the pointers you are absolutely guaranteed to have a vector lying around with a whole ton of dangling pointers in it.