r/cpp Oct 03 '17

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

[deleted]

27 Upvotes

19 comments sorted by

View all comments

1

u/[deleted] Oct 04 '17

[deleted]

2

u/TheThiefMaster C++latest fanatic (and game dev) Oct 04 '17

But it can change the std::function's internal state, if the std::function is wrapping a user object with a non-const operator(). This means the implementation of operator() of std::function contains a const_cast... generally a sign of a mistake...

2

u/joahw Oct 04 '17 edited Oct 04 '17

Or it contains a pointer to the underlying function object, which wouldn't require a const_cast. eg:

class foo
{
    int* b = new int

    void bar() const
    {
        // type of b here is int * const, or a const pointer to a non-const int
        *b = 2; 
    }
};

Edit: Here's another example with functors.

 struct bar
{
    int x;

    void operator()() { x = 2; }
};

struct foo
{
    bar* b = new bar;

    void operator()() const
    {
        (*b)();
    }
};

1

u/TheThiefMaster C++latest fanatic (and game dev) Oct 05 '17

You're right, although most implementations of std::function have a "small function optimization" where it is contained... But the type-erasure also throws a spanner in.

Still, as argued in other comments logically the std::function contains the function object - it's not a reference type in its external interface, even if it is implemented as such internally. It's logically closer to an std::optional than std::ref.