isocpp / isocpp/CppCoreGuidelines

Suggestion: Guidance for calling non const methods from const via pointers (std::propagate_const, gsl::owner,not_null...)

Open
#566 3 comments 4 reactions 1 assignee View on GitHub

@hsutter is already working on this.

Since Nov 28, 2016.

open
Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

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.() ?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.