0

This is with C++20 (-std=c++20), GCC 10.2.0 and Clang 11.1.0.

I have a class Graph with a data member prefix_to_presufs. In my code, I make a std::unique_ptr to a Graph like so:

auto gr{std::make_unique<Graph>()};

then I try to do this:

auto less{[&p2p{gr->prefix_to_presufs}](PreSuf l, PreSuf r) -> bool {
        return p2p[l.suf()].size() < p2p[r.suf()].size();
}};

However, GCC gives me this error:

filename.cc: In function ‘int main()’:
filename.cc:236:39: error: cannot capture ‘{gr.std::unique_ptr<{anonymous}::Graph, std::default_delete<{anonymous}::Graph> >::operator->()->{anonymous}::Graph::prefix_to_presufs}’ by reference
  236 |  auto less{[&p2p{gr->prefix_to_presufs}](PreSuf l, PreSuf r) -> bool {
      |                                       ^

I want to know if what I'm trying to do perhaps is not compliant with the standard and Clang is being unnecessarily permissive, or if this is rather just a GCC bug.

In response to comments below, if I try initializing like this instead: &p2p = gr->prefix_to_presufs, my code compiles.

user2373145
  • 332
  • 2
  • 14
  • 2
    Can you provide a [mcve] showing how `Graph` and `prefix_to_presufs` are declared? The error message is pretty self-explanatory: "*error: cannot capture ‘{prefix_to_presufs}’ by reference*". Do you have the same error with `[&p2p = gr->prefix_to_presufs]`? Can you capture `gr` itself without error? Then you could use `gr->prefix_to_presufs[]` inside the lambda body instead of `p2p[]` – Remy Lebeau May 07 '21 at 00:29
  • 1
    What happens if you use `=` for the initializer instead? As in `&p2p = gr->prefix_to_presufs` – Some programmer dude May 07 '21 at 00:34
  • @Someprogrammerdude my code compiles if I use `=`. Does that tell you anything? – user2373145 May 07 '21 at 10:47
  • @RemyLebeau Using `=` for initialization indeed makes GCC compile my code. What does that tell you? Is a minimal example still needed? – user2373145 May 07 '21 at 10:48

0 Answers0