1

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?

Tomson
  • 73
  • 5
  • 1
    google about dependency injection – Iłya Bursov Mar 21 '22 at 01:57
  • 1
    Your last sentence is very similar to dependency injection. However I'd suggest to use reference then you don't need to take care of `nullptr`. – Louis Go Mar 21 '22 at 01:59
  • I think if you learned why globals are considered bad, you would be able to come up with an answer to this on your own. Every project is different, the design choices are up to you, but you can only make those choices if you fully understand them. – Taekahn Mar 21 '22 at 02:02
  • There is some discussion of the pros and cons (yes, there are both) of using globals or statics at https://stackoverflow.com/questions/484635/are-global-variables-bad – Peter Mar 21 '22 at 02:11

1 Answers1

1

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);
BBing
  • 152
  • 5
  • Thanks for your answer, singleton would be soultion!, but I forgot to mention multithread situation.. There will be one memory pool for one thread. so it would be array of memory pool objects. should I wrap array of pool up to one class like `MepList`? – Tomson Mar 21 '22 at 02:44
  • It's hard to say... Did you mean each memory pool in each thread manage the different set of memorys? Is there any assosiation for each memory pool? If yes, wrap the pool objects to a array class may be better. If not, I think pass/construct the pool objects to each thread may be better. – BBing Mar 22 '22 at 11:30
  • By the way, you can try a `MemoryPoolManager` class, the class manage all memory pools, no matter multithread or singlethread, no matter multipools or singlepool. In your case, each thread can aquire a memory pool by MemoryPoolManager interface. – BBing Mar 22 '22 at 11:34