Skip to content

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

Open
@jmlundberg

Description

@jmlundberg

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: microsoft/GSL#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.() ?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions