-1

Is it possible to have a function that takes a reference to an argument that has a default, where the default is instantiated using its default constructor?

For example:

void g(Foo &f = Foo()) {}

This does not work, but I feel that it conveys my intention quite clearly.

yasgur99
  • 756
  • 2
  • 11
  • 32
  • 1
    That just-amended little non-const lvalue reference makes a world of difference. The answer is no, it isn't possible. And it may convey your intention well to you, but the rest of us... not so much. My crystal ball tells me you're using this recursively? – WhozCraig Aug 31 '22 at 03:11
  • @WhozCraig do you know why it isn't possible? – yasgur99 Aug 31 '22 at 03:12
  • 3
    You're trying to assign a non-const lvalue reference to a temporary value `Foo()`. These references essentially bind to *named variables*. There is no named variable here and thus it will not compile. https://stackoverflow.com/questions/18565167/non-const-lvalue-references – DXPower Aug 31 '22 at 03:16
  • 1
    A non-const lvalue reference cannot bind to a temporary. Basically that's the principle reason. – WhozCraig Aug 31 '22 at 03:17

1 Answers1

2

References to non-const cannot bind to temporary values, and Foo() is a temporary Foo object.

If you don't need to modify the passed object, then you can make f a reference to const:

void g(const Foo& f = Foo()) {}

If you do modify the passed reference, then using a temporary doesn't make much sense, since you'll would be modifying an object that would go out of scope as soon as the function returns.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52