Search code examples
gccattributesgcc-warning

__attribute__ ((warn_unused_result)) does not produce warnings for shared_ptr


Note: Added example below and updated title after comment about reproducibility.

We are trying to improve our codebase by supplying attributes to our functions.

on some functions we have added the attribute:

__attribute__ ((warn_unused_result))

At some points we deliberatly put some code that should produce a warning as we do not use the result of the function. e.g.

shared_ptr<type> functionName() __attribute__ ((warn_unused_result));
functionName(); // this should produce a warning

However no warnings are produced. Are these warnings suppressed by default or are there some other dependencies to make this work.

I found some info here: https://www.linuxquestions.org/questions/programming-9/gcc-warn_unused_result-attribute-917158 via google, but this does not point me in a direction on why it does not work for non-standard features.

As four our setup:

  • g++ version 4.9.2
  • Debian version 8.6
  • enabled warning flags on build:

    -Wall -Wextra -Wconversion -Wshadow -Weffc++
    

Here is an example that reproduces this issue:

#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;
}

and 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)

Any help or pointers would be much appreciated.

Regards, Jan Jaap


Solution

  • This evidently is a compiler bug specific to C++ that is present until GCC 6.3 and fixed in GCC 7.1. Upgrading GCC would seem to be your only solution.