brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.5 KiB · 43da9ae Raw
47 lines · plain
1.. title:: clang-tidy - bugprone-misleading-setter-of-reference2 3bugprone-misleading-setter-of-reference4=======================================5 6Finds setter-like member functions that take a pointer parameter and set a7reference member of the same class with the pointed value.8 9The check detects member functions that take a single pointer parameter,10and contain a single expression statement that dereferences the parameter and11assigns the result to a data member with a reference type.12 13The fact that a setter function takes a pointer might cause the belief that an14internal reference (if it would be a pointer) is changed instead of the15pointed-to (or referenced) value.16 17Example:18 19.. code-block:: c++20 21  class MyClass {22    int &InternalRef;  // non-const reference member23  public:24    MyClass(int &Value) : InternalRef(Value) {}25 26    // Warning: This setter could lead to unintended behaviour.27    void setRef(int *Value) {28      InternalRef = *Value;  // This assigns to the referenced value, not changing what InternalRef references.29    }30  };31 32  int main() {33    int Value1 = 42;34    int Value2 = 100;35    MyClass X(Value1);36 37    // This might look like it changes what InternalRef references to,38    // but it actually modifies Value1 to be 100.39    X.setRef(&Value2);40  }41 42Possible fixes:43  - Change the parameter type of the "set" function to non-pointer type (for44    example, a const reference).45  - Change the type of the member variable to a pointer and in the "set"46    function assign a value to the pointer (without dereference).47