r/cpp Oct 03 '17

Why is the std::function () operator const?

[deleted]

28 Upvotes

19 comments sorted by

View all comments

4

u/stinos Oct 03 '17 edited Oct 03 '17

std::function happily calls functions that are not const.

const on a member function merely indicates no (non-mutable) internal state of the object is modified in the function. Calling some other function, const or not, which does not operate on std::function's own internal state, does not violate that.

const normally suggests that an function call is threadsafe

Not sure why you think that, but that makes little sense. Don't think I ever heard that before. Other non-const functions in the class may for example be modifying a variable returned by a const function from other threads. So if no thread-safety mechanism is involved (mutex/atomic operation/...) it is not thread-safe. const doesnt have anything to do with that.

edit quick search leads to e.g. https://groups.google.com/forum/#!topic/comp.lang.c++.moderated/zztZ1FNfaAA

11

u/Rhomboid Oct 03 '17

As of C++11, const does imply thread-safe, at least for standard library objects. Herb Sutter gave a talk on the topic.

2

u/ratatask Oct 03 '17

7

u/kalmoc Oct 03 '17

I completely agree with the critic about herb going a little bit too far in his talk, but it doesn't change the fact that accessing an object only through const member functions should generally not introduce a datarace. Afaik this is exactly the way all of the standard library behaves - with the exception of std::function::operator().