这是一个小程序:
#include <iostream>
#include <string>
#include <cstdlib>
void Exit_With_Error(std::string const& error_message);
int main(){
Exit_With_Error("Error X occurred.");
return 0;
}
void Exit_With_Error(std::string const& error_message){
std::cerr << error_message << std::endl;
exit(EXIT_FAILURE);
return;
}
如您所见,函数Exit_With_Error实际上从未返回。我想我应该添加一个属性来更好地说明这一点。文档 here ,让我相信它应该是这样的:
#include <iostream>
#include <string>
#include <cstdlib>
[[noreturn]] void Exit_With_Error(std::string const& error_message);
int main(){
Exit_With_Error("Error X occurred.");
return 0;
}
[[noreturn]] void Exit_With_Error(std::string const& error_message){
std::cerr << error_message << std::endl;
exit(EXIT_FAILURE);
return;
}
但是,它无法编译:
main.cpp:6:1: error: expected unqualified-id before ‘[’ token
main.cpp: In function ‘int main()’:
main.cpp:9:37: error: ‘Exit_With_Error’ was not declared in this scope
main.cpp: At global scope:
main.cpp:13:1: error: expected unqualified-id before ‘[’ token
不过我已经成功了!
#include <iostream>
#include <string>
#include <cstdlib>
__attribute__((noreturn)) void Exit_With_Error(std::string const& error_message);
int main(){
Exit_With_Error("Error X occurred.");
return 0;
}
__attribute__((noreturn)) void Exit_With_Error(std::string const& error_message){
std::cerr << error_message << std::endl;
exit(EXIT_FAILURE);
return;
}
我的问题: 如何让 [[attribute]] 语法发挥作用?我正在 gcc 上使用 c++11 标志进行编译。例如,
g++ -std=c++11 -o main main.cpp
但是它不起作用。我的编译器版本是 4.7.2。 这种工作方式是否正确,或者我应该争取更简单的语法?
最佳答案
没有。通用属性直到 4.8 版本才在 GCC 中实现
这可以在这里看到:
http://gcc.gnu.org/gcc-4.7/cxx0x_status.html
http://gcc.gnu.org/gcc-4.8/cxx0x_status.html
关于c++ - C++11 属性在 g++ 4.7.2 上工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474651/