3

Can I assign to function parameter which is const reference to QString a default value? Something like

 void someFun(const QString & param = "")

Actually, I can, it compiles and runs as expected, but I', a little bit confused with it, 'cos not sure what is going on under the hood. So here I have reference to a QString object that is created on the stack and have lifetime of this function?

Borrimoro
  • 529
  • 3
  • 9
  • 19
  • 2
    The important part in this is actually the `const` keyword, it wouldn't work without it. – Some programmer dude Jul 09 '13 at 12:16
  • 1
    automatic conversion does its job that's it. This is equivalent of: `void someFun(const QString &param = QString(""));`. const reference make automatic objects usable as arguments. – Marek R Jul 09 '13 at 12:17
  • What will happen is that a new temporary object will be constructed on the stack and a reference to it will be passed to the function. The problem you may spot is that the temporary object will go out of scope and will be destroyed while you may still be using the reference you got. – Caladan Jul 09 '13 at 12:25
  • 2
    = QString() is how it's usually done – Frank Osterfeld Jul 09 '13 at 12:28
  • @JoachimPileborg can you write more about why it won't work without const? – Borrimoro Jul 09 '13 at 14:47
  • @Borrimoro because `QString()` (or `QString("")`) is a temporary variable. Check [here](https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects) – rsht Jul 30 '15 at 09:22

0 Answers0