File: stringview-nullptr.rst

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (63 lines) | stat: -rw-r--r-- 1,895 bytes parent folder | download | duplicates (18)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
.. title:: clang-tidy - bugprone-stringview-nullptr

bugprone-stringview-nullptr
===========================
Checks for various ways that the ``const CharT*`` constructor of
``std::basic_string_view`` can be passed a null argument and replaces them
with the default constructor in most cases. For the comparison operators,
braced initializer list does not compile so instead a call to ``.empty()``
or the empty string literal are used, where appropriate.

This prevents code from invoking behavior which is unconditionally undefined.
The single-argument ``const CharT*`` constructor does not check for the null
case before dereferencing its input. The standard is slated to add an
explicitly-deleted overload to catch some of these cases: wg21.link/p2166

To catch the additional cases of ``NULL`` (which expands to ``__null``) and
``0``, first run the ``modernize-use-nullptr`` check to convert the callers to
``nullptr``.

.. code-block:: c++

  std::string_view sv = nullptr;

  sv = nullptr;

  bool is_empty = sv == nullptr;
  bool isnt_empty = sv != nullptr;

  accepts_sv(nullptr);

  accepts_sv({{}});  // A

  accepts_sv({nullptr, 0});  // B

is translated into...

.. code-block:: c++

  std::string_view sv = {};

  sv = {};

  bool is_empty = sv.empty();
  bool isnt_empty = !sv.empty();

  accepts_sv("");

  accepts_sv("");  // A

  accepts_sv({nullptr, 0});  // B

.. note::

  The source pattern with trailing comment "A" selects the ``(const CharT*)``
  constructor overload and then value-initializes the pointer, causing a null
  dereference. It happens to not include the ``nullptr`` literal, but it is
  still within the scope of this ClangTidy check.

.. note::

  The source pattern with trailing comment "B" selects the
  ``(const CharT*, size_type)`` constructor which is perfectly valid, since the
  length argument is ``0``. It is not changed by this ClangTidy check.