cppbestpractices
cppbestpractices copied to clipboard
Clarify that marking certain member variables const can hinder performance
In the 03-Style document, I read the following sentence:
If the member variable is not expected to change after the initialization, then mark it const.
However, we know that if, for example, we mark a container as const
, we prevent it from being moved, possibly hindering performance. Marking fields as const
is useful to enforce invariants; however, it "interferes" with performance. If both const correctness and performance are important, one could leave the field non-const, make it private and define a field getter.
class MyClass { public: MyClass(int t_value) : m_value{t_value} { }
private: const int m_value{0}; };
hey @andreastedile look at the code, here the attribute m_value is initialized with 0 and it was being expecting that in the future the value will be same (variable is not expected to change after the initialization). so, if by mistakely you try to assign with any other value it will not happen if and only if we declare it as const then your mistake will not cause any future problem. please let me know if you got my point or not.
@mallikpramod You have misunderstood this post. I am suggesting that the part discussing const correctness of an object field should be updated to clarify that, if an object is expected to be moved, then its fields must not be marked const if they are containers. A field being const would prevent the whole object from being moved (thus inducing a copy), hindering performance. I am not asking for a clarification of what const correctness is. You may want to watch this video, made by one of the major contributors of this repository, to understand what I am talking about: https://youtu.be/dGCxMmGvocE?t=838
@andreastedile Well, thanks! Now i got what you exactly talking about i.e. where to use and not to use const for better performance, the video was really good. As you posted it under issue section i thought you get confused with const, but you wanna to clarify about const i really got to know a lot thanks again.