Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4998

Function parameters should not be of type "std::unique_ptr<T> const &"

    XMLWordPrintable

    Details

    • Message:
      Replace this use of "unique_ptr" by a raw pointer or a reference (possibly const).
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C++
    • Irrelevant for Languages:
      ABAP, APEX, C#, C, Cobol, CSS, Flex, Go, HTML, Java, JavaScript, Kotlin, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Ruby, Rust, Scala, Solidity, Swift, T-SQL, TypeScript, VB.Net, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      1min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources
    • CppCoreGuidelines:
      R.32

      Description

      If you use std::unique_ptr<T> const & for a function parameter type, it means that the function will not be able to alter the ownership of the pointed-to object by the unique_ptr:

      • It cannot acquire ownership of the pointed-to object (this would require a parameter of type std::unique_ptr<T>)
      • It cannot transfer the object ownership to someone else (this would require a std::unique_ptr<T> &).

      That means the function can only observe the pointed-to object, and in this case passing a T* (if the unique_ptr can be null) or a T& (if it cannot) provides the same features, while also allowing the function to work with objects that are not handled by a unique_ptr (E.G. objects on the stack, in a vector, or in another kind of smart pointer), thus making the function more general-purpose.

      Noncompliant Code Example

      using namespace std;
      void draw(unique_ptr<Shape> const &shape); // Noncompliant
      
      void drawAll(vector<unique_ptr<Shape>> v)
      {
        for (auto &shape : v) {
            if (shape) {
              draw(shape);
            }
        }
      }
      

      Compliant Solution

      using namespace std;
      void draw(Shape const &shape); // Compliant
      
      void drawAll(vector<unique_ptr<Shape>> v)
      {
        for (auto &shape : v) {
            if (shape) {
              draw(*shape);
            }
        }
      }
      

      See

      • C++ Core Guidelines R.32 - Take a unique_ptr<widget> parameter to express that a function assumes ownership of a widget

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              loic.joly Loïc Joly
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: