Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple instances of a class with constant variables use same memory for constants?

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?

like image 799
replicant Avatar asked Jan 18 '23 11:01

replicant


1 Answers

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;
like image 96
Mysticial Avatar answered Jan 31 '23 08:01

Mysticial