Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I’ve lost track of how many times I’ve listened to Kate Gregory extol the virtues of const-ing all the things, but people still don’t systematically add it

Adding const to _function-local_ variables only really matters when you "leak" a pointer or ref, whether mutable or const, to a function or variable the compiler can't optimize away:

    std::size_t sz = 4096;
    const std::size_t &szRef = sz;
    some_opaque_func(szRef);
    if (sz != 4096) std::abort(); // cannot be optimized away unless sz is const
as there is no way to know if something obtains a mutable ref to sz down the line.

In other cases like RVO, adding const is actually detrimental as it prevents the move-constructor from being selected (likewise with the move assignment operator).

Rust _needs_ to have const by default due to its aliasing model ("only one mutable ref per object") and you can't have cheap bound checks without this. But that, too, is a tradeoff (some classes of programs are hard to code in Rust)



Pretty sure the std::abort() can't be optimized away if sz is mutable since it's legal for some_opaque_func() to cast away szRef's const and modify sz via that. sz itself needs to be const for the if statement to be removable as dead code.

https://cpp.godbolt.org/z/Pa3bMh9Ee shows that both GCC and Clang keep the abort when sz is not const. Add const and the abort goes away.


Yes, that is what I said - sorry if this wasn't clear


Looking back I think I might have misread your comment and thought you meant that the const on the reference was what mattered. Sorry about that!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: