gpt4 book ai didi

c++ - 对于内联函数和 constexpr 函数, "obey ODR"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:22 26 4
gpt4 key购买 nike

我刚读到 constexpr 和 inline 函数遵循一个定义规则,但它们的定义必须相同。所以我试了一下:

inline void foo() {
return;
}

inline void foo() {
return;
}

int main() {
foo();
};

错误:'void foo()' 的重新定义,

constexpr int foo() {
return 1;
}

constexpr int foo() {
return 1;
}

int main() {
constexpr x = foo();
};

错误:'constexpr int foo()' 的重新定义

那么究竟是什么意思,constexpr 和 inline 函数可以服从 ODR?

最佳答案

I just read that constexpr and inline functions obey one-definition rule, but they definition must be identical.

这是引用不同翻译单元中的内联函数。在您的示例中,它们都在同一个翻译单元中。

这包含在 draft C++ standard3.2 一个定义规则 [basic.def.odr] 说:

There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

并包括以下项目符号:

  • each definition of D shall consist of the same sequence of tokens; and

关于c++ - 对于内联函数和 constexpr 函数, "obey ODR"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com