0

I want to:

  const int default_value = 0;
  const auto do_something = [&](const int& value = default_value) {};

Or less simplified:

struct Value {
  Value();
  Value(const Value&) = delete;
  Value& operator=(const Value&) = delete;

  int value = 0;
};


void function() {
  Value default_value;
  const auto do_something = [&](const Value& value = default_value) {};
  do_something();
}

This gives error: local variable ‘default_value’ may not appear in this context (onlinegdb.com) or default argument references local variable 'default_value' of enclosing function (CLion).

I'm sure I can get around this by removing the param default value or using overloaded plain functions instead of lambdas. But I was hoping to understand why these don't work.

Especially since this works just fine:

  Value default_value;
  const auto do_something = [&](const Value& value) {};
  do_something(default_value);

I know default_value in do_something(default_value) is a non-const, non-ref, non-ptr, l-value.

And I think default _value in (const Value& value = default_value) is also a non-const, non-ref, non-ptr, l-value. So why would one work and not the other?

Likewise, ptr params give the same errors.

  const int default_value = 0;
  const int* default_value_ptr = &default_value;
  const auto do_something = [&](const int* value = default_value_ptr) {};
junvar
  • 10,160
  • 2
  • 23
  • 40

0 Answers0