Closed domino-succ closed 7 years ago
Is it not working? What error is being thrown? It might be because sc->Get
is not marked const. Otherwise I don't see why the lambda wouldn't work.
sc->Get
is const. But when I removed const
for fn
like this auto fn = [&count,](StateCounter* sc) { count += sc->Get(100); };
there is no error again. Why I can't make the parameter const
? And the document also suggests the parameter should be const reference
, right?
See this stack overflow post: http://stackoverflow.com/questions/9994029/c-why-dont-const-functions-force-const-ness-on-member-pointers
Seems like marking find_fn
const only guarantees that you cannot change what the pointer your lambda is being called with is pointing to, but you can still dereference it and change the value at that memory address. What you can't do is use a lambda like this:
[&count](StateCounter*& sc) {...}
Because then you would be able to change what sc
is pointing to. I tried this on my machine and it did indeed give me a compiler error.
I think it's not really worth trying to accommodate the special case of the value being a raw pointer, and changing it into a read-only pointer (which I think is an entirely different concept in C++).
The document said that for
find_fn
, thefn
should implementoperator ()
that should not modify the contents of the value. Could you give an example for that? For example, there is acuckoohash<string, class* > mp
, I have aGet(string& key, int& count)
like this:The above example is not supposed to work. How should I implement the
opertator()
function to make it work?