c++ - 为什么 constexpr 静态成员(类型类)需要定义?

标签 c++ c++11 static-members c++14 constexpr

==> 在 coliru 上查看完整的代码片段和编译.

我有一个 LiteralType补课constexpr requirements :

struct MyString
{
    constexpr MyString(char const* p, int s) : ptr(p), sz(s) {}
    constexpr char const* data() const { return ptr; }
    constexpr int         size() const { return sz;  }

    char const *ptr = 0;
    int  const  sz  = 0;
};

我将它用作 constexpr static成员变量:

struct Foo
{
    int size() { return str_.size(); }

    constexpr static MyString str_{"ABC",3};
};

int main()
{
  Foo foo;
  return ! foo.size();
}

但是链接器说:
(Clang-3.5 和 GCC-4.9)

undefined reference to `Foo::str_'

我必须定义constexpr static成员!
(我没有指定构造函数参数)

constexpr MyString Foo::str_;

但是,如果 constexpr static 成员是 int,则不必在类定义之外定义该成员。这是我的理解,但我不确定...

问题:

  • 为什么 int 不需要在类声明之外定义,但 MyString 需要这个?
  • 在头文件中定义constexpr static 成员是否有缺点?
    (我只提供我的库作为头文件)

最佳答案

One Definition rule告诉我们不能有多个 odr-used 的定义程序中的变量。所以如果一个变量是 odr-used 那么你需要定义它但是你不能在头文件中定义它因为它可能被包含在整个程序中不止一次。 Odr-use 违规不需要诊断消息,因此您可以违反此规则,编译器没有义务通知您。

在您的情况下,您确实使用了 str_,并且您不能在头文件中包含该定义,因为这会违反一个定义规则,因为它可以在头文件中多次包含程序。

有趣的是,如果您执行了以下操作,它就不会被使用:

return str_.size_;

因此您不需要定义变量 which can have some odd consequences in some examples .我怀疑这是否能长期解决您的问题。

ODR 规则包含在 C++ 标准草案部分 3.2 中,他们说:

A variable x whose name appears as a potentially-evaluated expression ex is odr-used unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.19) that does not invoke any non-trivial functions and, if x is an object, ex is an element of the set of potential results of an expression e, where either the lvalue-to-rvalue conversion (4.1) is applied to e, or e is a discarded-value expression (Clause 5). this is odr-used if it appears as a potentially-evaluated expression (including as the result of the implicit transformation in the body of a non-static member function (9.3.1)).[...]

所以 str_ 产生一个常量表达式,左值到右值的转换不应用于表达式 str_.size() 并且它不是一个丢弃的值表达式,所以它是 ODR 使用的,因此需要定义 str_

另一方面,左值到右值的转换应用于表达式 str_.size_,因此它不是 odr-used 并且不需要 str_ 来被定义。

关于c++ - 为什么 constexpr 静态成员(类型类)需要定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29397864/

相关文章:

c++ - 为什么 const 方法不能返回非常量引用?

c++ - VS2013中的SFINAE

c++ - 这可能是内存泄漏吗?

c++ - 如何结合 boost::spirit::lex 和 boost::spirit::qi?

c++ - 是否可以禁止对一小段 C++ 代码使用某些寄存器?

c++ - 为什么不允许 `std::uniform_int_distribution<uint8_t>` 和 `std::uniform_int_distribution<int8_t>`?

Java:类问题

java - 静态成员的顺序在 Swing 中是否敏感?

java - 静态方法内存分配

c++ - 如何一次获取所有重复的符号链接(symbolic link)器错误?