【发布时间】:2018-08-29 08:25:27
【问题描述】:
注意:添加了下面的示例,并在对可重复性发表评论后更新了标题。
我们正在尝试通过为我们的函数提供属性来改进我们的代码库。
在某些功能上我们添加了属性:
__attribute__ ((warn_unused_result))
在某些时候,我们故意放置一些应该产生警告的代码,因为我们不使用函数的结果。 例如
shared_ptr<type> functionName() __attribute__ ((warn_unused_result));
functionName(); // this should produce a warning
但是没有产生警告。这些警告是默认抑制的,还是有一些其他依赖项可以使这项工作。
我在这里找到了一些信息:https://www.linuxquestions.org/questions/programming-9/gcc-warn_unused_result-attribute-917158 via google,但这并不能说明为什么它不适用于非标准功能。
作为我们的四个设置:
- g++ 版本 4.9.2
- Debian 8.6 版
-
在构建时启用警告标志:
-Wall -Wextra -Wconversion -Wshadow -Weffc++
以下是重现此问题的示例:
#include <iostream>
#include <memory>
std::shared_ptr<std::string> function(int b) __attribute__ ((warn_unused_result));
int other(int b) __attribute__ ((warn_unused_result));
int main()
{
auto lResult = function(3); // not expect warning
std::cout << lResult->c_str() << " is the result" << std::endl;
std::cout << function(4)->c_str() << " is the result too." << std::endl; // not expect warning
function(5); // expect warning but this warning is not given.
auto lOther = other(3); // not expect warning
std::cout << lOther << " is the result" << std::endl;
std::cout << other(4) << " is the result too." << std::endl; // not expect warning
other(5); // expect warning and it is given.
return 0;
}
std::shared_ptr<std::string> function(int b)
{
auto lString = std::make_shared<std::string>("::" + std::to_string(b) + "::");
return lString;
}
int other(int b)
{
return 5 * b;
}
和 CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(ShowCase)
add_definitions("-std=c++14")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Wall -Wextra -Wconversion -Wshadow -Weffc++")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -Wall -Wextra -Wconversion -Wshadow -Weffc++")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -Wall -Wextra -Wconversion -Wshadow -Weffc++ ")
set(CMAKE_CXX_FLAGS_DEBUG "-g -Wall -Wextra -Wconversion -Wshadow -Weffc++")
add_executable(ShowCase main.cpp)
任何帮助或指点将不胜感激。
问候, 扬亚普
【问题讨论】:
标签: gcc attributes gcc-warning