gpt4 book ai didi

c++ - std::pair 数组的聚合初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:37 28 4
gpt4 key购买 nike

正如所怀疑的那样,用花括号初始化 std::pair 不起作用,因为 std::pair 不是聚合。

std::pair <int, int> p = {1,2}; // Doesn't work

但是,初始化 std::pair 数组效果很好(在 gcc 4.9 中有警告)

std::pair <int, int> a_p[] = {
{1,2},
{3,4},
{5,6}
}; // Works fine

为什么会这样?

编辑:此问题已被标记为可能重复 C++11 aggregate initialization for classes with non-static member initializers但是,这个问题没有谈论非静态成员初始化器,据我所知,std::pair 有一个用户定义的构造函数。引自 http://en.cppreference.com/w/cpp/header/utility ,

template <class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;

T1 first;
T2 second;
pair(const pair&) = default;
pair(pair&&) = default;

constexpr pair();
pair(const T1& x, const T2& y);
template<class U, class V> pair(U&& x, V&& y);
template<class U, class V> pair(const pair<U, V>& p);
template<class U, class V> pair(pair<U, V>&& p);
template <class... Args1, class... Args2>
pair(piecewise_construct_t,
tuple<Args1...> first_args, tuple<Args2...> second_args);

pair& operator=(const pair& p);
template<class U, class V> pair& operator=(const pair<U, V>& p);
pair& operator=(pair&& p) noexcept(see below);
template<class U, class V> pair& operator=(pair<U, V>&& p);

void swap(pair& p) noexcept( noexcept(swap(first, p.first)) &&
noexcept(swap(second, p.second)) );
};

最佳答案

自 C++11 发布以来,类类型的聚合式初始化(​​“统一初始化”)在过去 5 年中一直是合法的。

旧版本的 gcc 默认使用古老的 C++03 标准(或更旧的 C++98),但了解 C++11,因此在某些情况下会应用 C++11 规则明确的。这是警告的意思:

warning: extended initializer lists only available with -std=c++11 or -std=gnu++11

一些更旧版本的 gcc 可能会应用它们自己的(C++11 之前的)扩展,因此会给出不同的警告。

您应该(至少)在 C++11 模式下编译,或者使用默认为 C++11 或 C++14 的现代编译器,例如 gcc 6.1。

关于c++ - std::pair 数组的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195356/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com