Unsolved Why does const auto& lead to empty lists?
-
Given that const references extend the lifetime of object instances (see e.g. Herb Sutter's explanation), why does the following code dump an empty list?
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); const auto& list = QStringList() << "abc" << "xyz"; qDebug() << list; return a.exec(); }
Change to "const auto list =[...]", and the code works as expected.
-
Hi,
What compiler are you using ?
This works with
Apple LLVM version 9.0.0 (clang-900.0.39.2)
-
Both MinGW 5.3 and VS 2015 show this behavior in my tests.
-
This post is deleted! -
What about VS2017 ?
-
@Asperamanca said in Why does const auto& lead to empty lists?:
const references extend the lifetime of object instances (see e.g. Herb Sutter's explanation)
Wow, TIL. I must say this feature feels unintuitive to me, however.
EDIT: Actually, this felt weird because I've never found a reason to define a const-ref local variable. However, this feature makes some sense when I think about a const-ref function parameter.
-
@JKSH said in Why does const auto& lead to empty lists?:
@Asperamanca said in Why does const auto& lead to empty lists?:
const references extend the lifetime of object instances (see e.g. Herb Sutter's explanation)
Wow, TIL. I must say this feature feels unintuitive to me, however.
EDIT: Actually, this felt weird because I've never found a reason to define a const-ref local variable. However, this feature makes some sense when I think about a const-ref function parameter.
So you never do stuff like this?
for(const auto& item : container) { // Do stuff }
Because, theoretically you could now remove that item from the container within that loop (although this would rarely be a good idea), and the reference would not be invalid.
-
@SGaist said in Why does const auto& lead to empty lists?:
What about VS2017 ?
Same as VS2015 and MinGW
-
@Asperamanca said in Why does const auto& lead to empty lists?:
So you never do stuff like this?
for(const auto& item : container) { // Do stuff }
I do, I do.
I just I think of this like I do with function parameters, but I think of function parameters differently from local variables inside a function block (like
const auto& list = ...;
). Once I remember they're basically the same, it now makes sense.