GCC和Clang对constexpr构造函数的不同行为 [英] GCC and Clang different behaviors on constexpr constructor

查看:150
本文介绍了GCC和Clang对constexpr构造函数的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于此结构:

  struct Wrapper {
int value;

constexpr explicit Wrapper(int v)noexcept:value(v){}
Wrapper(const Wrapper& that)noexcept:value(that.value){}
};

此功能:

  constexpr Wrapper makeWrapper(int v)
{
return Wrapper(v);
}

以下代码无法为Clang(Apple LLVM 7.3.0版) ,但是对于 -Wall -Wextra -Werror -pedantic-errors :<$ p

>编译GCC(4.9+) pre> constexpr auto x = makeWrapper(123);

Clang抱怨非constexpr构造函数'Wrapper'不能用于常量表达式。哪个编译器是正确的?

解决方案

虽然复制或移动时返回 Wrapper makeWrapper()可以省略,它需要与C ++ 14存在。现有的拷贝构造函数是非 - constexpr ,它的存​​在禁止创建一个隐式移动构造函数。因此,我认为clang是正确的:你需要使复制构造函数 constexpr



注意使用C ++ 17代码可能会正确:在一些上下文中有一个建议使复制限制是强制的: P0135r0 。然而,似乎这种变化还没有落在工作文件中。它可能会在本周登陆,虽然(感谢@NicolBolas指出,它不存在,但)。我没有在邮件中看到更新的文章。


For this struct:

struct Wrapper {
    int value;

    constexpr explicit Wrapper(int v) noexcept : value(v) {}
    Wrapper(const Wrapper& that) noexcept : value(that.value) {}
};

And this function:

constexpr Wrapper makeWrapper(int v)
{
    return Wrapper(v);
}

The following code fails to compile for Clang (Apple LLVM version 7.3.0), but compiles fine for GCC (4.9+), both with -Wall -Wextra -Werror -pedantic-errors:

constexpr auto x = makeWrapper(123);

Clang complains that "non-constexpr constructor 'Wrapper' cannot be used in a constant expression." Which compiler is right?

解决方案

Although the copy or move when returning Wrapper from makeWrapper() can be elided, it is required to exist with C++14. The existing copy constructor is non-constexpr and its existence inhibits creation of an implicit move constructor. As a result I think clang is right: you'd need to make the copy constructor a constexpr.

Note that with C++17 the code might become correct: there is a proposal to make copy-elision mandatory in some contexts: P0135r0. However, it seems this change hasn't landed in the working paper, yet. It may land this week, though (thanks to @NicolBolas for pointing out that it isn't there, yet). I haven't seen an updated paper in the mailing.

这篇关于GCC和Clang对constexpr构造函数的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆