Answer the question
In order to leave comments, you need to log in
Is there a difference, at a low level, between a class with static fields and a global class instance?
Let's say there are two options:
Option 1. Structure with static fields
// MyPool.h
struct MyPool {
static unsigned int capacity;
static unsigned int numOfAllocatedObjects;
}
// MyPool.cpp
unsigned int MyPool::capacity {1024};
unsigned int MyPool::numOfAllocatedObjects {0};
// MyPool.h
struct MyPool {
unsigned int capacity {1024};
unsigned int numOfAllocatedObjects {0};
}
extern MyPool MyGlobalPool;
// MyPool.cpp
MyPool MyGlobalPool {};
Answer the question
In order to leave comments, you need to log in
No difference.
You can also check it yourself. Technology these days is easy. Here: https://godbolt.org/z/PKWPdY4nn
As you can see, both are compiled into almost the same instructions:
eax, DWORD PTR MyGlobalPool[rip+4]
...
eax, DWORD PTR MyPool1::numOfAllocatedObjects[rip]
Most likely there is no low-level difference if we are talking about one glob. object in the second case:
https://godbolt.org/z/YaWccvPx3
It seems to me that if this is a pool for memory allocation, etc., then preferably closer to the second option, because it is possible to create different pools of the same type in one program. Rather, something like shared_ptr on the pool of the allocator is even better ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question