gpt4 book ai didi

c++ - VS2019 内联函数的一些问题

转载 作者:行者123 更新时间:2023-11-27 22:32:30 24 4
gpt4 key购买 nike

我正在 VS2019 中做一些关于 C++ 内联函数的(可能是奇特的)实验:

来源1:

#include "pch.h"

inline int inline_func(int i) {
return i;
}

void testinline1()
{
inline_func(0);
}

来源2:

#include "pch.h"

inline int inline_func(int i) {
return i*i ;
}

void testinline2()
{
inline_func(0);
}

主要来源:

#include "pch.h"

inline int inline_func(int i);
int main(int argc,char* argv[])
{
int i = inline_func(2);
}

根据 http://en.wikipedia.org/wiki/Inline_function 的“内联函数的存储类”部分,

In C++, a function defined inline will, if required, emit a function shared among translation units, typically by putting it into the common section of the object file for which it is needed. The function must have the same definition everywhere, always with the inline qualifier.

source1和source2中inline_func的定义不同所以应该有错误,但是VS2019中没有这个错误。

main() 中 i 的结果是 2,它来自 source1 中的 inline_func,这似乎是构建过程的随机选择,因为如果我在 source1 中注释 testinline1,那么 i 将从 source1 中的 inline_func 变为 4如果不在同一源中使用,则不会出现在目标文件中。当我在 source2 中评论 testinline2 时, inline_func 也会出现预期的 undefined symbol 错误。

为什么会发生这些?这是 C++ 没有涵盖的地方还是只有 MSVC 没有涵盖的地方?

回答后更新:

这是一个更好的例子:

来源1:

#include "pch.h"

int non_inline_func();
inline int inline_func2() {
return non_inline_func();
}

static int non_inline_func()
{
return 1;
}

int public_func1()
{
return inline_func2();
}

来源2:

#include "pch.h"

int non_inline_func();
inline int inline_func2() {
return non_inline_func();
}

static int non_inline_func()
{
return 2;
}

int public_func2()
{
return inline_func2();
}

主要来源:

#include "pch.h"

int public_func1();
int public_func2();

void TestInline()
{
int i =public_func1();
int j= public_func2();
}

结果是 i=j=1。内联函数的定义在这里是一样的。这应该违反:https://en.cppreference.com/w/cpp/language/definition#One_Definition_Rule

name lookup from within each definition finds the same entities (after overload-resolution)

最佳答案

来自 this One Definition Rule (ODR) reference :

If all these requirements are satisfied, the program behaves as if there is only one definition in the entire program. Otherwise, the program is ill-formed, no diagnostic required.

[强调我的]

如果您有 ODR 违规(因为这两个定义不相同),编译器不必发出警告或错误消息。

关于c++ - VS2019 内联函数的一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245063/

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