c++compiler-warningsclang++uniform-initialization

Clang: no warning with -Wdangling-gsl and curly braces initialization, bug in clang?


Consider the following snippet:

#include <string>
#include <string_view>

int main() {
  auto str = std::string{};

  auto sv1 = std::string_view(str + "!"); // <- warning :)
  std::string_view sv2(str + "!");        // <- warning :)
  std::string_view sv3 = str + "!";       // <- warning :)

  auto sv4 = std::string_view{str + "!"}; // <- no warning :(
  std::string_view sv5{str + "!"};        // <- no warning :(
}

Compiled with flags -std=c++17 -Wdangling-gsl. Tested in clang 12.0.1 and trunk in compiler explorer.

As expected, in sv1, sv2 and sv3, str + "!" triggers the warning:

Object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]

However in sv4 and sv5 the same expression, but using {}, does not.

Is this an expected behaviour of using {}? Is this a bug in clang? Am I just missing something?


Solution

  • This is a bug in clang's diagnosis. The use of curly braces in your last two cases does not 'fix' the dangling pointer issue.

    By way of 'confirmation', the Code Analysis tool (static analyser) in Visual Studio/MSVC gives the following warnings for all five svX variables:

    warning C26449: gsl::span or std::string_view created from a temporary will be invalid when the temporary is invalidated (gsl.view).
    warning C26815: The pointer is dangling because it points at a temporary instance which was destroyed.