I know that global/extern variables are bad, still not sure why exactly though.
But some cases, I can't figure out how to deal with this problem without using extern.
For example, in the server application I'm developing, I need every class, every source file to access list of all client objects. So that I can sending packets to that client whenever I need to..
Also, I need to declare memory pool object to increase performance of allocating/deallocating overlapped struct.(I cannot use smart pointer in this case because I have to free memory frequently). But there has to be only one memory pool object obviously so I have to declare it as gloabl/extern.
How can I approach this problem?
Should I declare shared_ptr or raw pointer in every class, and pass the pointer of object when class is constructed?
CodePudding user response:
Singleton can help. There is a simple example:
static MemPool *MemPool::getMemPool()
{
static MemPool g_mempool = MemPool(/***...***/);
return &g_mempool;
}
Memory *MemPool::allocMemFromPool(const size_t &size)
{
//...
}
auto data = getMemPool()->allocMemFromPool(1024);