简体   繁体   English

包含std :: queue的类的值初始化

[英]Value-initialization of class containing std::queue

Here is a MCVE: 这是一个MCVE:

#include <queue>

struct S
{
    std::queue<int> q;
    int r;
};

int main()
{
    S s{};
}

With gcc 6.x -std=c++14 -pedantic I get warnings 随着gcc 6.x -std=c++14 -pedantic我收到警告

<source>:11:9: warning: converting to 'std::queue<int>' from initializer list would use explicit constructor 'std::queue<_Tp, _Sequence>::queue(_Sequence&&) [with _Tp = int; _Sequence = std::deque<int, std::allocator<int> >]'
 S s{};
     ^
<source>:11:9: note: in C++11 and above a default constructor can be explicit            ^

In gcc 7.x, or clang , there are no warnings. 在gcc 7.x或clang中,没有警告。

My question is: Is this code actually correct or not; 我的问题是:这段代码是否真的正确无误; and if it is correct, what are the warnings trying to warn me about exactly? 如果它是正确的,有什么警告试图警告我的确切?

This is, in fact, ill-formed under the standard as published, which depicts queue with an explicit default constructor. 事实上,这是在已发布的标准下形成的,它描述了具有显式默认构造函数的queue

S is an aggregate; S是一个集合; S s{}; is aggregate initialization and doesn't call the default constructor of S . 是聚合初始化,不调用S的默认构造函数。 Instead, since no explicit initializer is specified for q , it's copy-initialized from an empty initializer list, which is ill-formed because copy-list-initialization selected an explicit constructor. 相反,由于没有为q指定显式初始化程序,因此它是从空的初始化程序列表中复制初始化的,这是错误的,因为复制列表初始化选择了显式构造函数。

GCC 7 gave queue a non-explicit default constructor (which is how it should be anyway), which is why you aren't seeing the error. GCC 7为queue了一个非显式的默认构造函数(无论如何应该是这样),这就是为什么你没有看到错误。 Similarly, the default constructor of libc++'s queue has always been non-explicit. 类似地,libc ++ queue的默认构造函数一直是非显式的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM