Search code examples
c++cpp-core-guidelinesguideline-support-library

How to use gsl::span to fix No array to pointer decay warning?


I am attempting to resolve the following warning.

warning C26485: Expression 'pNMLink->item.szUrl':
No array to pointer decay. (bounds.3...)

This warning is caused by the following code.

auto pNMLink = reinterpret_cast<PNMLINK>(pNMHDR);
ShellExecuteW(nullptr, L"open", pNMLink->item.szUrl, nullptr, nullptr, SW_SHOWNORMAL);

The extremely limited documentation of the C++ Core Guidelines suggests that the solution is to use a span.

array decay -- use span (from the GSL)

Unfortunately, it gives no information on how to construct that span from the array.

I have tried the following.

gsl::span<wchar_t> url(pNMLink->item.szUrl);

I have tried a number of other options as well. They all result in the same exact warning. What magical incantation do I need to use to avoid the warning?


Solution

  • This would appear to be an error in the static analysis tool. How do I know? Because you don't get this warning if you do this:

    int arr[10];
    gsl::span<int> sp1(arr);
    

    But you do get the warning if you do this:

    struct Arr { int arr[10]; };
    Arr test;
    gsl::span<int> sp2(test.arr);
    

    gsl::span has a constructor that takes array parameters by reference, so when you pass an array directly, there should be no decaying. As shown by sp1, which gives no warning. And there's no C++ reason why fetching the array from a struct would provoke decay when using an automatic variable does not.

    So clearly, this is a bug in the analysis tool, a false positive.