Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify that marking certain member variables const can hinder performance #147

Open
andreastedile opened this issue Jun 7, 2022 · 3 comments

Comments

@andreastedile
Copy link

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.

@mallikpramod
Copy link

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.

@andreastedile
Copy link
Author

andreastedile commented Aug 25, 2022

@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

@mallikpramod
Copy link

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants