Is the global vector just meant to list all the objects in memory or do you actually delete objects from the vector. In the later case ForEveR gave a good answer. In the former case, if the code would work, none of the shared_ptr you create would get deleted until the end of the program because they are stored in a global vector. In this case just keep it simple and use old style pointers and add them at the constructor and delete in destructor. For efficiency it's better to change the vector data type. E.g.,
#include<iostream>
#include<memory>
#include<unordered_set>
class A;
std::unordered_set<A*> alpha;
class A{
public:
A(): x(9)
{
alpha.insert(this);
}
~A(){
alpha.erase(this);
}
private:
int x;
};
Example test:
int main(){
std::shared_ptr<A> a= std::make_shared<A>();
std::cout << "Number of objects: " << alpha.size() << std::endl;
{
std::shared_ptr<A> a1= std::make_shared<A>();
std::shared_ptr<A> a2= std::make_shared<A>();
std::cout << "Number of objects: " << alpha.size() << std::endl;
}
std::cout << "Number of objects: " << alpha.size() << std::endl;
}
Number of objects: 1
Number of objects: 3
Number of objects: 1