In C++, we can assign an object to a non-const reference. So this works:
Foo &foo = Foo();
But, C++ doesn't allow a temporary to be assigned to a non-const reference. So this is not allowed:
Bar::Bar(Foo &foo = Foo()) {}
But this is allowed
Bar::Bar(const Foo &foo = Foo()) {}
I have three questions here:
- What is the scope of foo in the last case? Does it live even after the constructor is exited. From what I read, the lifetime of a temporary is modified if it is assigned to a const reference, in which case it takes up the lifetime of the reference is it assigned to. What is the lifetime of the default argument, in this case foo?
- I tried the second example in MSVC and it didn't complain. I also noticed that the lifetime of the temporary was still extended. So I could use foo after the constructor exited. What is that about?
- My scenario demands the default argument to constructor in this manner and I will need to modify the argument in the constructor (so I cannot make it const). And I also need to use foo after the constructor has exited. What is the best design to cater to this scenario?
Thanks in advance.