【问题标题】:auto and copy constructor: what's wrong? [duplicate]自动和复制构造函数:怎么了? [复制]
【发布时间】:2016-07-28 08:29:38
【问题描述】:

考虑以下代码:

#include<queue>
#include<type_traits>

int main() {
    std::queue<int> q;
    auto p{q};
    static_assert(std::is_same<decltype(q), decltype(p)>::value, "fail");
}

它与 GCC 5.1.0(参见 here)和 clang 3.8.0(参见 here)编译得很好,但它不适用于 GCC 4.9.0(参见here)。
进一步分析,似乎是因为p的类型被推断为std::initializer_list
例如,如果有人替换该行,它就会起作用:

auto p{q};

随行:

decltype(q) p{q};

我不确定哪个是正确的(尽管 GCC 5.1.0 符合我的预期),这就是我在这里询问的原因。
期望p 的类型为std::queue&lt;int&gt; 是否正确?

【问题讨论】:

  • 这是特殊情况。 Mayers 在 C++11/14 的“有效的现代 C++”中写到了这一点。这是由于汽车的特殊类型扣除规则。当自动声明变量的初始化器用大括号括起来时,推导的类型是 std::initial izer_list。如果不能推导出这样的类型(例如,因为大括号初始化器中的值是不同的类型)
  • auto 是 c++11 功能,据我所知,gcc 仅从 5.1 开始完全支持它

标签: c++ c++11 gcc clang auto


【解决方案1】:

This is a known defect in the standard auto{} 推导出为 std::initializer_listThere is a proposed change to fix this defect.

较新的 gcc 和 clang 实现了建议的解决方案,而 gcc-4.9 没有。

【讨论】:

    【解决方案2】:

    没有。 {q} 计算结果为 std::initializer_list。没有什么可以告诉编译器你可能想要别的东西,所以 auto 使用那个。

    还有decltype(q)decltype({q})不一样;

    【讨论】:

      猜你喜欢
      • 2013-10-13
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2018-02-03
      • 2013-08-04
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多