简体   繁体   English

编译器优化问题

[英]Compiler optimization issue

Compiling the following cause T::f() to be optimized-out without any warning or error: 编译以下内容会导致T::f()得到优化,而没有任何警告或错误:

#include <iostream>

struct T
{
    int t;
    void f(); //undefined..
};

int main()
{
    T t;
    t.t = 1;
    //t.f(); //<-- compiler-error only when used, otherwise optimized-out
    std::cout << t.t;
    return 0;
}

Background: I used stub-declarations for functions in a class with intention to later define and use them. 背景:我在类中的函数中使用了存根声明,以便稍后定义和使用它们。 'Later' never came, and my code compiled & the compiler issued no warnings or errors about these stubs. “后来”再也没有出现,我的代码已编译,并且编译器未发出有关这些存根的警告或错误。

Is this expected from the compiler?; 这是编译器所期望的吗? shouldn't the compiler at least issue warnings? 编译器至少不应发出警告吗?

This is not an "optimization". 这不是“优化”。 C++ compiler lets you declare anything that you wish, provided that the declaration is valid syntactically, and does not reference undefined types. C ++编译器允许您声明所需的任何内容,前提是该声明在语法上有效,并且不引用未定义的类型。 This is not specific to member functions: non-member functions and global variables can be declared without providing a corresponding definition. 这并非特定于成员函数:可以在不提供相应定义的情况下声明非成员函数和全局变量。

It turns out that neither the compiler nor the linker are in a good position to complain about unfulfilled declaration. 事实证明,无论是编译器还是链接器都没有资格抱怨未完成的声明。 Even issuing a warning would be problematic due to the possibility of separate compilation. 由于可能会单独进行编译,因此即使发出警告也会造成问题。

Compiler will not complain, because it knows that another cpp file may provide the definition, and by the time the linker runs, the declaration is gone: linker works with definitions and references, while declarations are for the compiler. 编译器不会抱怨,因为它知道可以由另一个cpp文件提供定义,并且到链接器运行时,声明就消失了:链接器可以使用定义和引用,而声明用于编译器。

From a comment: 来自评论:

There are hundreds (or even thousands) "not called by app" functions in system .h files. 系统.h文件中有数百个(甚至数千个)“应用未调用”功能。 The compiler doesn't know where the code resides: either in your .cpp source, or in precompiled .obj/.o, or in .dll/.so etc.etc. 编译器不知道代码在哪里:在您的.cpp源代码中,还是在预编译的.obj / .o中,或者在.dll / .so等中。 It's linker's duty, not the compiler's one. 这是链接器的职责,而不是编译器的职责。 So the compiler silently ignores every signature without "body". 因此,编译器无提示地忽略了没有“ body”的每个签名。 – user4419802 – user4419802

The compiler hasn't optimized anything out because there was nothing there to optimize out in the first place. 编译器没有优化任何东西,因为最初没有任何东西可以优化。 When you declared void T::f(); 当您宣布void T::f(); all you did was add a method signature to the compiler's internal dictionary, if you like. 如果愿意,您所做的只是在编译器的内部字典中添加方法签名。 You never gave the method a corresponding body and you never called it so it simply 'never happened'. 您从未为该方法指定相应的主体,也从未对其进行调用,因此它只是“从未发生”。

编译器不知道是否要在另一个编译单元中声明T::f() ,它也不在乎,因为它“知道”,如果不声明,则会出现链接器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM