如果不是 intializer_list,什么是花括号封闭列表?

What Is a Curly-Brace Enclosed List If Not an intializer_list?(如果不是 intializer_list,什么是花括号封闭列表?)

本文介绍了如果不是 intializer_list,什么是花括号封闭列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里问了一个问题:initializer_list return 的Lifetime Extension 涉及非功能性代码:

I asked a question here: Lifetime Extension of a initializer_list return involving the non-functional code:

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

我相信 lambda 试图返回一个 initializer_list(这很糟糕,不要那样做.)但我得到了一个 评论:

I believed the lambda was trying to return an intializer_list (that's bad, don't do that.) But I got a comment:

这不是 initializer_list,它是一个初始化列表.两种不同的东西.

It's not an initializer_list, it's an initializer list. Two different things.

我只是认为,任何时候你做一个花括号列表,你都是在创建一个 intializer_list.如果这不是正在发生的事情,那么大括号中的列表是什么?

I just thought that any time you did a curly-braced list you were creating an intializer_list. If that's not what's happening, what is a list in curly-braces?

推荐答案

这里有三个不同但相关的概念:

There are three distinct, but related concepts here:

  1. braced-init-list:在某些上下文中与大括号括起来的列表相关的语法规则.

  1. braced-init-list: The grammatical rule associated with curly-brace-enclosed lists in certain contexts.

Initializer list:在 list-initialization 中使用的 braced-init-list 初始化器的名称.

Initializer list: The name for the braced-init-list initializer used in list-initialization.

std::initializer_list:包装临时数组的类,该数组是在涉及 braced-init-lists 的某些上下文中创建的.

std::initializer_list: A class wrapping a temporary array which is created in some contexts involving braced-init-lists.

一些例子:

//a braced-init-list and initializer list, 
//but doesn't create a std::initializer_list
int a {4}; 

//a braced-init-list and initializer list,
//creates a std::initializer_list
std::vector b {1, 2, 3};

//a braced-init-list and initializer list,
//does not create a std::initializer_list (aggregate initialization)
int c[] = {1, 2, 3};

//d is a std::initializer_list created from an initializer list
std::initializer_list d {1, 2, 3};

//e is std::initializer_list<int>
auto e = { 4 };

//f used to be a std::initializer_list<int>, but is now int after N3922
auto f { 4 };

您可能想阅读 N3922,它已更改一些涉及 autostd::initializer_list 的规则.

You might want to read N3922, which changed some of the rules involving auto and std::initializer_list.

这篇关于如果不是 intializer_list,什么是花括号封闭列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果不是 intializer_list,什么是花括号封闭列表?

基础教程推荐