Reputation: 25
I have a class that contains a color attribute, and I want to use an enumeration to handle it. Since at runtime my program may create thousands of instances of this class, where is the best place to declare the enumeration in order to optimize memory usage ?
At the moment, my class declaration looks like this :
class Node
{
public :
//constructors, methods, etc...
enum class Color : char{WHITE, GREY, RED, GREEN}
protected :
//Some private attributes
Color _color = Color::WHITE;
};
I know this is an acceptable way to do it, my question is : will it bring performances down when i got like 100k instances of this class ?
Upvotes: 0
Views: 43
Reputation: 5844
As with any data type, the enum itself won't take up storage in your objects, it's instances of the enum that are stored. (Regarding this, there is no difference between enum
and enum class
.) So moving the enum out of the class does not make any difference in this respect.
So in your case, the color_
member takes up storage space. If there are subclasses where you don't need that, you might want to reconsider your class design. Otherwise, you are fine!
Upvotes: 1
Reputation: 129374
I'm guessing you are concerned with class
in the declaration of enum class
vs enum
.
The enum class
and old style enum
will generate exactly the same code and behave exactly the same in the "backend" of the compiler. The distinction happens in the semantic analysis (type checking) by the compiler (more strict checking compared to "traditional" enum
types, so you can't do int x = WHITE;
or enum { A, B }; Color c = A;
).
Upvotes: 1