0

Im interested in the following (psudocode):

void set_it_up {
  A a{};

  //OK to use a...
  
  execute_it_later([&]{return a;});//When gets executed later, a has been destroyed...

  //here a also OK
}

Now Im well aware that this is usually fine to do something like this - if the lambda is used before the object gets destroyed.

But, is it possible to avoid capturing a somehow (making the code malformed) ? (lets just say I want to avoid 'accidents' to happend in the future by mistakenly capturing a temporary that gets de-allocated early).

Can I somehow openly show that A is a temporary that it shouldn't get a reference binding to ?

I can modify A as much as I want.

darune
  • 10,480
  • 2
  • 24
  • 62
  • 1
    No you can't. There's nothing in C++ that can be used to indicate that an object cannot be captured by reference. C++ does very little to prevent yourself from shooting yourself in the foot. – Sam Varshavchik Nov 05 '20 at 12:53
  • Is this really a different question from the [one](https://stackoverflow.com/questions/64694558/avoid-implicit-capture-of-this) you asked before? – cigien Nov 05 '20 at 12:53
  • @cigien I do think this is broader somehow - I tried to think about ways I could rework the overall design while still allowing for '[&]' capture – darune Nov 05 '20 at 12:59
  • 1
    The tool to avoid mistake is explicit capture. You should avoid implicit capture in production code. By using explicit capture, you tell the compiler which variables could be used and for each one, you specify if you want it by reference or copy. **In fact, this is the main purpose of explicit capture**. – Phil1970 Nov 05 '20 at 13:00
  • Most compilers would warn on similar code if it was straight-forward enough. Running some static analyzer would help catch more cases (one would probably catch this one as well). But there is no general 100% solution other than enforcing some really strict guidelines (prohibiting the construct entirely or limiting it) – Dan M. Nov 05 '20 at 13:01
  • Would it matter if `a` was `const`? – Ted Lyngmo Nov 05 '20 at 13:02
  • @TedLyngmo I can modify all parts of the code, so I could it make it const no problem - although it can't be 'constexpr' or compile time constant – darune Nov 05 '20 at 13:04
  • @darune Ok, I was thinking of the validity of the code. Would making `a` `const` make the `const&` capture prolong the lifetime of `a`.? – Ted Lyngmo Nov 05 '20 at 13:06
  • @TedLyngmo do you think that would be a solution or what do you mean ? – darune Nov 05 '20 at 13:07
  • 1
    @darune If it was true, I guess it could be a solution in those cases where it's ok to make it `const` - but when thinking about it, I don't see how it could be true anyway, so... just a sidetrack. – Ted Lyngmo Nov 05 '20 at 13:09

0 Answers0