Skip to content

Allow multiple calls with shared pointers arguments (not being a reference parameter) for rule R.21 #2226

@jansen-tiobe

Description

@jansen-tiobe

I would like to thank Danny Havenith for bringing up this example and suggesting this improvement.

Rule R.21 ("Prefer unique_ptr over shared_ptr unless you need to share ownership") has enforcement:

(Simple) Warn if a function uses a Shared_pointer with an object allocated within the function, but never returns the Shared_pointer or passes it to a function requiring a Shared_pointer&. Suggest using unique_ptr instead.

Now consider the following code:

void Registry::add( shared_pointer< Participant> w);

void f( Registry &r1, Registry &r2)
{
    const auto p = make_shared<Participant>();
    r1.add( p);
    r2.add( p);
}

According to the enforcement this code will be flagged, but it is not possible to use a unique_ptr in this case because the pointer is shared between 2 function calls.

Hence, I suggest to extend the enforcement as follows:

_(Simple) Warn if a function uses a Shared_pointer with an object allocated within the function, but:

  • never returns the Shared_pointer and
  • never passes it to a function requiring a Shared_pointer& and
  • does not pass it to a function as a Shared_pointer argument (by value or reference) more than once.

Suggest using unique_ptr instead._

What are your thoughts? Should I just create a pull request for this change?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions