【问题标题】:Function returning constexpr does not compile返回 constexpr 的函数无法编译
【发布时间】:2011-12-08 09:42:54
【问题描述】:

为什么不编译:
string 作为返回类型会不会有问题?

constexpr std::string fnc()
{
    return std::string("Yaba");
}

【问题讨论】:

    标签: c++ compiler-errors c++11 constexpr


    【解决方案1】:

    采用指向char 的指针的std::string 的构造函数不是constexpr。在constexpr 函数中,您只能使用constexpr 的函数。

    【讨论】:

    • 谢谢,以前不知道。
    • +1 而那个构造函数不能是constexpr 的原因是它有副作用(即分配),不能在编译时进行。
    • @smallB:常量表达式构造函数必须是 1. 声明为 constexpr 2. 有一个成员初始化器部分只涉及潜在的常量表达式和 3. 有一个空的主体。在我看来,std::string 必须违反 #2。
    • @smallB:好的。我从来没有说过相反的话。
    • @smallB 您不能为std::string 使用任意长度const char*constexpr 构造函数并确保安全。虽然字符串文字确实是常量表达式,但有很多 const char* 类型的东西不是常量表达式。想到std::stringc_str 成员。 constexpr 上的重载无法区分两者。
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 2021-11-28
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多