Reference to lambda function output

In Scott Meyers' "Overview of the new C++11/14", he shows

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <numeric>
#include <vector>

int main() {
	const auto sortedInts = []()->std::vector<int> {
		std::vector<int> v(10);
		std::iota(v.begin(), v.end(), -5);
		return v;
	}();
}


I tried replacing auto with auto& because I felt that should be more efficient. It works when I do so:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <numeric>
#include <vector>

int main() {
	const auto& sortedInts = []()->std::vector<int> {
		std::vector<int> v(10);
		std::iota(v.begin(), v.end(), -5);
		return v;
	}();
	for (int i : sortedInts)
		std::cout << i << ' ';  // -5 -4 -3 -2- 1 0 1 2 3 4
}

This is perfectly fine, right? And it is more efficient, right? Why did Scott Meyers not use reference in the above example (almost suggesting that you shouldn't)?
Last edited on
This is perfectly fine, right?


No. You are returning a reference to an object that no longer exists. 'v' has a lifetime only in the lambda function.

EDIT: actually the function IS returning by value, you just are taking a reference to the returned object. So yeah that's fine. Whoops.

And it is more efficient, right?


Probably not. But even if it were, the difference wouldn't be noticeable.

With the advent of move constructors and move assignment, returning by value is practically free. Don't be so afraid of it.

EDIT 2: Also, the compiler will likely construct the object 'in place' if you assign by value rather than have a reference.
Last edited on
-> No. You are returning a reference to an object that no longer exists. 'v' has a lifetime only in the lambda function.

Perhaps Scott Meyers hastily thought the same thing when he wrote his example without the reference? When is a case where you would not want to use a reference? After all, it is const. Even if it wasn't const, I still don't see why not use a reference anyway.
Last edited on
To me the question is less "why would you not want to use a reference?" and more "why would you not want to use an object?"
The context of Scott Meyers' example is that such an object, which would require lines of code to construct, would otherwise not be const after the construction. You can imagine his example being more complex. So by using a lambda function, it can be made const. That's all.
Last edited on
Topic archived. No new replies allowed.