【问题标题】:C++ inline function and external function with the same name give an unexpected result同名的 C++ 内联函数和外部函数给出了意想不到的结果
【发布时间】:2015-11-04 23:18:34
【问题描述】:

以下代码不违反一个定义规则,但它给出了意想不到的结果:

Test.hpp

class Test
{
    public:
        int test();
};

Test1.cpp

#include "Test.hpp"

int Test::test()
{
    return 1;
}

int test1() // expected to return 1
{
    Test a = Test();
    return a.test();
}

Test2.cpp

#include "Test.hpp"

inline int Test::test() // doesn't violate ODR
{
    return 99;
}

int test2() // expected to return 99
{
    Test a = Test();
    return a.test();
}

ma​​in.cpp

#include <iostream>

int test1();
int test2();

int main()
{
    std::cout << test1() << std::endl;
    std::cout << test2() << std::endl;
}

我希望它打印“1 99”,但它总是打印“1 1”。

关于Test::test的两个定义,因为其中一个是内联定义,所以也不违反一个定义规则。

所以这个程序是有效的,但它没有打印出预期的结果......

这个程序有什么问题吗?还是我对 ODR 规则有误解? (参考 C++ 标准会很有帮助)。

【问题讨论】:

  • Regarding two definitions of Test::test, since one of them is an inline definition, it does not violate ODR你是从哪里得到这个想法的?
  • 好吧,我认为它不违反 ODR,因为在 C++ 规范的 ODR 部分中没有提到这个问题。 “如果具有外部链接的函数在一个翻译单元中声明为内联,则应在其出现的所有翻译单元中声明为内联;不需要诊断。”在函数说明符部分提到,它不处理 ODR。

标签: c++ one-definition-rule


【解决方案1】:

您不能将函数定义为inline 和非inline

如果一个具有外部链接的函数是 在一个翻译单元中声明为 inline,则应在其出现的所有翻译单元中声明为 inline; 不需要诊断。

([dcl.fct.spec]/4)

【讨论】:

  • 感谢您的回答。但是您提到的声明未在规范的 ODR 部分中说明。那么我可以说我提供的代码不违反 ODR 吗? (它违反了函数说明符规则,但不违反 ODR)
  • @SHH 我不能说它是否。 ODR 的措辞具有“非内联功能”。因此它隐含地假设一个函数不能同时是内联和非内联的;它必须是其中之一。当您尝试将同一函数声明为内联和非内联时,ODR 甚至没有意义。
猜你喜欢
  • 2014-06-22
  • 1970-01-01
  • 2014-05-24
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
相关资源
最近更新 更多