efficient / libcuckoo

A high-performance, concurrent hash table
Other
1.62k stars 275 forks source link

Example of find_fn(key, fn) #68

Closed domino-succ closed 7 years ago

domino-succ commented 7 years ago

The document said that for find_fn, the fn should implement operator () that should not modify the contents of the value. Could you give an example for that? For example, there is a cuckoohash<string, class* > mp, I have a Get(string& key, int& count) like this:

int Get(string& key, int& count) {
    auto fn = [&count,](const StateCounter*& sc) { count += sc->Get(100); };
    mp.find_fn(key, fn);
    return count;
} 

The above example is not supposed to work. How should I implement theopertator() function to make it work?

manugoyal commented 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.

domino-succ commented 7 years ago

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?

manugoyal commented 7 years ago

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++).