initializer_list 返回的生命周期延长 [英] Lifetime Extension of a initializer_list return
问题描述
所以我有一个返回类型为 auto
的 lambda,我遇到了支持 initializer_list
的数组在此处被销毁的问题:
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}; };
我将像这样使用 lambda:
I will be using the lambda like this:
auto bar = foo(1, 2, 3);
for(const auto& i : bar) cout << i << endl;
我正在从事的一项工作将所有 lambda 表达式作为单个语句作为其编码标准的一部分(请随意表达您的愤怒.)我想我可以通过以下方式解决这个问题:
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:
- 给
foo
一个vector int
的返回类型,但这弄乱了它的通用性:const auto foo = [](const auto& a, const auto& b, const auto& c) ->向量
{返回{a,b,c};} - 只需编写一个模板化函数,该函数构造一个
vector
并返回它:template
向量 Tfoo(const T& a, const T& b, const T& c){ return {a, b, c};}
- Giving
foo
a return type ofvector 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}; }
- 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}; }
是否可以将这些变量强制放入一个容器中,谁的支持不会在一行中全部销毁,以便我可以保留带有 auto
返回类型的 lambda?
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?
推荐答案
库基础 TS v2 有 std::experimental::make_array
,肯定能满足你的要求:
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
今天,您可以使用 common_type
:
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}; };
这篇关于initializer_list 返回的生命周期延长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!