1.. title:: clang-tidy - bugprone-stringview-nullptr 2 3bugprone-stringview-nullptr 4=========================== 5Checks for various ways that the ``const CharT*`` constructor of 6``std::basic_string_view`` can be passed a null argument and replaces them 7with the default constructor in most cases. For the comparison operators, 8braced initializer list does not compile so instead a call to ``.empty()`` 9or the empty string literal are used, where appropriate. 10 11This prevents code from invoking behavior which is unconditionally undefined. 12The single-argument ``const CharT*`` constructor does not check for the null 13case before dereferencing its input. The standard is slated to add an 14explicitly-deleted overload to catch some of these cases: wg21.link/p2166 15 16To catch the additional cases of ``NULL`` (which expands to ``__null``) and 17``0``, first run the ``modernize-use-nullptr`` check to convert the callers to 18``nullptr``. 19 20.. code-block:: c++ 21 22 std::string_view sv = nullptr; 23 24 sv = nullptr; 25 26 bool is_empty = sv == nullptr; 27 bool isnt_empty = sv != nullptr; 28 29 accepts_sv(nullptr); 30 31 accepts_sv({{}}); // A 32 33 accepts_sv({nullptr, 0}); // B 34 35is translated into... 36 37.. code-block:: c++ 38 39 std::string_view sv = {}; 40 41 sv = {}; 42 43 bool is_empty = sv.empty(); 44 bool isnt_empty = !sv.empty(); 45 46 accepts_sv(""); 47 48 accepts_sv(""); // A 49 50 accepts_sv({nullptr, 0}); // B 51 52.. note:: 53 54 The source pattern with trailing comment "A" selects the ``(const CharT*)`` 55 constructor overload and then value-initializes the pointer, causing a null 56 dereference. It happens to not include the ``nullptr`` literal, but it is 57 still within the scope of this ClangTidy check. 58 59.. note:: 60 61 The source pattern with trailing comment "B" selects the 62 ``(const CharT*, size_type)`` constructor which is perfectly valid, since the 63 length argument is ``0``. It is not changed by this ClangTidy check. 64