我最近了解了该[[noreturn]]属性,并想尝试在我现有的代码片段之一上实现它。
我将该属性添加到一个没有任何return;关键字的 void 返回类型函数中。但是,我收到此错误:
[ 17%] Building CXX object CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o\n/home/turgut/Desktop/CppProjects/videoo-render/src/opengl/text_render.cpp:7:25: error: function \xe2\x80\x98const void OpenGL::Text::set_background(int, int, float, int, int, int, int, float, std::string*)\xe2\x80\x99 declared \xe2\x80\x98[[noreturn]]\xe2\x80\x99 but its first declaration was not\n 7 | [[noreturn]] const void Text::set_background(\n | \n\nmake[2]: *** [CMakeFiles/Renderer.dir/build.make:132: CMakeFiles/Renderer.dir/src/opengl/text_render.cpp.o] Error 1\nmake[1]: *** [CMakeFiles/Makefile2:277: CMakeFiles/Renderer.dir/all] Error 2\nmake: *** [Makefile:136: all] Error 2\n\nRun Code Online (Sandbox Code Playgroud)\n我使用的是 c++ 20+ 所以我不认为版本有问题。
\n我的使用有什么问题[[noreturn]]以及我应该如何正确使用它?我是否缺少这方面的知识?
这是有问题的函数:
\n[[noreturn]] void Text::set_background(\n int x, int y, float z,\n int w, int h, \n int gw, int gh,\n float ang, std::string* hex_color\n){\n background = new Background(x-w, y-h);\n background->color = (*hex_color).c_str();\n\n background->bg_texture = new Texture(\n x - 10, (1000 - y) + 10, w, -h ,gw, gh\n );\n\n background->bg_texture->init(ang, z, nullptr);\n}\nRun Code Online (Sandbox Code Playgroud)\n我还尝试在其他一些类似的函数上使用它,但得到了类似的结果。
\n这些属性需要位于函数的实际声明中,即类内头文件中的属性Text。
对于函数的定义(实现),您不需要再次使用该属性。
有几个不同的注意事项,使用返回类型const的限定符void是没有意义的。
而该[[noreturn]]属性就是告诉编译器该函数根本不返回。例如,该std::exit函数不返回,因此被标记为该属性。
您的函数确实返回(我假设?),因此该属性对该函数没有意义。