If I have a class that defines multiple constant variables like so...
class SomeClass {
public:
SomeClass() : SOME_CONSTANT(20), ANOTHER_CONSTANT(45), ANOTHER_CONSTANT2(25), ANOTHER_CONSTANT2(93) { }
private:
const int SOME_CONSTANT;
const int ANOTHER_CONSTANT;
const int ANOTHER_CONSTANT2;
const int ANOTHER_CONSTANT3;
Will multiple instances of this class be optimized to point to the same memory for the constants? or can I save memory by making each constant static?
If they are not static, then no, they will not be optimized out. Each instance will have space for all the constants. (In fact, I don't think the compiler is even allowed to combine them in any way.)
If you do declare them static, they are in global memory and not in each instance. So yes, it will use less memory.
EDIT:
If you want to make them static constants, it should be done like this:
class SomeClass {
public:
SomeClass(){ }
private:
static const int SOME_CONSTANT;
static const int ANOTHER_CONSTANT;
static const int ANOTHER_CONSTANT2;
static const int ANOTHER_CONSTANT3;
};
const int SomeClass::SOME_CONSTANT = 20;
const int SomeClass::ANOTHER_CONSTANT = 45;
const int SomeClass::ANOTHER_CONSTANT2 = 25;
const int SomeClass::ANOTHER_CONSTANT3 = 93;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With