CppCoreGuidelines
CppCoreGuidelines copied to clipboard
Suggestion: Guidance for calling non const methods from const via pointers (std::propagate_const, gsl::owner,not_null...)
The section "Con.2: By default, make member functions const"
States under Enforcement: "Flag a member function that is not marked const, but that does not perform a non-const operation on any member variable."
Experience with resharper C++ which does this, is unfortunately that it's often doing more harm than good, because many/most pointer types (smart or plain, owning or not) do not propagate const, which makes resharper suggest possibly dangerously adding const. You all know it,
struct C{
std::unique_ptr<X> uptr;
Y* ptr;
void do(){
uptr->mutation();
ptr->mutation();
}
}
Adding const here becomes as bad as casting away const or making members mutable, and less visible. Also relates to thread safety implications of const.
I found no guidance related to this. A way to deal with this is http://en.cppreference.com/w/cpp/experimental/propagate_const , and something like
template<typename T,D> using cprop_uptr = std::propagate_const<std::unique_ptr<T,D>>
One useful practice (not for all?) is sticking to only const propagating pointer types as pointer members. (~~This may also be an argument for pushing the use of references over non-owning pointers.~~ edit, no - as jbcoe notes)
This somewhat relates to GSL issue 89: https://github.com/Microsoft/GSL/issues/89 (not_null<unique_ptr<>> doesn't work #89
) and indirectly to SO question http://stackoverflow.com/questions/33306553/gslnot-nullt-vs-stdreference-wrappert-vs-t
Has const propagation been considered for gsl smart pointers (owner<>, ... ) ? Or use operator.() ?
Re: "This may also be an argument for pushing the use of references over non-owning pointers." references have the same const-propagation issues as pointers when used as member variables.
Are you aware of any new insights or best practices on this? @jbcoe @AndrewPardoe
Hi, are there any updates on the topic? I think it's interesting to look at this issue from the perspective of "semantic const" instead of "syntactic const".