Lifetime Extension of a initializer_list return

2019-02-17 09:20发布

问题:

So I have a lambda who's return type is auto and I'm having issues with the array backing for an initializer_list being destroyed here:

const auto foo = [](const auto& a, const auto& b, const auto& c) { return {a, b, c}; };

I will be using the lambda like this:

auto bar = foo(1, 2, 3);

for(const auto& i : bar) cout << i << endl;

A job that I'm working has as part of their coding standard that all lambdas are single statements (feel free to express your outrage.) I think that I can get around this by:

  1. Giving foo a return type of vector int, but that messes up how nicely generic it is: const auto foo = [](const auto& a, const auto& b, const auto& c) -> vector<int> { return {a, b, c}; }
  2. Just writing a templatized function which constructs a vector<T> and returns it: template <typename T> vector<T> foo(const T& a, const T& b, const T& c){ return {a, b, c}; }

Is it possible to coerce these variables into a container, who's backing won't be destroyed all in one line so that I can keep the lambda with an auto return type?

回答1:

The library fundamentals TS v2 has std::experimental::make_array, which would certainly satisfy your requirements:

#include <experimental/array>
const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::experimental::make_array(a, b, c); };

More generally, template argument deduction for constructors would allow you to write:

const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::vector{a, b, c}; };
                      ^-- no template parameter required

Today, you could emulate this using common_type:

const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::vector<std::common_type_t<decltype(a), decltype(b), decltype(c)>>{a, b, c}; };