sha*_*han 6 c++ compiler-construction g++ compiler-warnings
#include <array>\n#include <iostream>\n#include <string>\nusing namespace std;\n\ntemplate <typename T> class MyClass {\npublic:\n // even not called, g() has -Wreturn-type warning\n double g() { std::cout << "g() called" << std::endl; }\n // only that f() is called, f() has -Wreturn-type warning otherwise, there is\n // no -Wreturn-type warning for it\n MyClass &f() { std::cout << "f() called" << std::endl; }\n // even not called and not instantiated, h() has -Wreturn-type warning\n // ! Interestingly, if i change return type from double to MyClass, there is\n // no -Wreturn-type warning if not called!!! Why? what the compiler is doing\n // under the hood?\n template <typename U> double h() {\n std::cout << "h() called" << sizeof(U) << std::endl;\n }\n};\n\nint main() {\n MyClass<double> m;\n // if f() is not called, there will be no -Wreturn-type warning\n // m.f();\n\n (void)m;\n}\nRun Code Online (Sandbox Code Playgroud)\n当我使用以下命令进行编译时:
\n#include <array>\n#include <iostream>\n#include <string>\nusing namespace std;\n\ntemplate <typename T> class MyClass {\npublic:\n // even not called, g() has -Wreturn-type warning\n double g() { std::cout << "g() called" << std::endl; }\n // only that f() is called, f() has -Wreturn-type warning otherwise, there is\n // no -Wreturn-type warning for it\n MyClass &f() { std::cout << "f() called" << std::endl; }\n // even not called and not instantiated, h() has -Wreturn-type warning\n // ! Interestingly, if i change return type from double to MyClass, there is\n // no -Wreturn-type warning if not called!!! Why? what the compiler is doing\n // under the hood?\n template <typename U> double h() {\n std::cout << "h() called" << sizeof(U) << std::endl;\n }\n};\n\nint main() {\n MyClass<double> m;\n // if f() is not called, there will be no -Wreturn-type warning\n // m.f();\n\n (void)m;\n}\nRun Code Online (Sandbox Code Playgroud)\n编译器问题:
\napp.cpp: In member function \xe2\x80\x98double MyClass<T>::g()\xe2\x80\x99:\napp.cpp:10:56: warning: no return statement in function returning non-void [-Wreturn-type]\n double g() { std::cout << "g() called" << std::endl; }\n ^\napp.cpp: In member function \xe2\x80\x98double MyClass<T>::h()\xe2\x80\x99:\napp.cpp:20:3: warning: no return statement in function returning non-void [-Wreturn-type]\n }\nRun Code Online (Sandbox Code Playgroud)\n在我的所有函数中,我都没有故意返回,\n我不使用 function f(),因此编译器不会发出警告,可能会被优化掉,这是可以理解的;但我都不用h(),为什么会有警告?
更奇怪的是,如果我将h()from的返回类型更改double为 to MyClass,警告就会消失
那么编译器会看到这些函数什么以及在编译过程中如何处理它们呢?
\n\n依赖返回类型可以(有时)是void:
template<class T>\nstruct X {\n std::conditional_t<sizeof(T)<17,void,int> f() {}\n};\nRun Code Online (Sandbox Code Playgroud)\nGCC 只是等待检查警告,直到知道类型为止。It\xe2\x80\x99s \xe2\x80\x9cobviously\xe2\x80\x9d 从未出现void在您的示例中,但请考虑条件可能是任意 constexpr 计算。