==> 在 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/