SonarCloud C++ False positive on naked new

Make sure to read this post before raising a thread here:

Then tell us:

  • What language is this for?

C++

  • Which rule?

Memory should not be managed manually cpp:S5025

  • Why do you believe it’s a false-positive/false-negative?

Issue description says that SonarCloud does not report a warning if the result of the naked new is directly passed as a function argument, which in this case is true; it is directly passed to the shared_ptr<> constructor. Additionally, the advice to replace with make_shared does not work in this case since the constructor of the class is private.

There is an issue for this reported here, but it has no update since 2021: [CPP-3252] - Jira

  • Are you using
    • SonarCloud
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
#include <memory>

class Example
{
    Example() {}


public:
    template <typename... Args>
    [[nodiscard]] static std::shared_ptr<Example> create(Args&&... args)
    {
        return std::shared_ptr<Example>(new Example(std::forward<Args>(args)...));
    }
};

int main()
{
    auto example = Example::create();
}
1 Like

Hello @kristoffer, and welcome to our community.

Thank you for reporting this issue with a nice example.

I agree the exception should apply in this case so I’ve raised a ticket to track this bug: [CPP-4508] - Jira

Regarding the private constructor, I feel there is also room for improvement in the rule description. It’s not directly obvious however how this should be done w.r.t. both rules S5025 and S5950. I’ve raised [CPP-4509] - Jira to look at this aspect.

In the meantime, you may be interested in this C++ Core Guideline: C.50: Use a factory function if you need “virtual behavior” during initialization. For the specific case you posted, you can ignore the inheritance of the example presented in the core guideline.

HTH

Hello Marco,

Thank you for the feedback! I will follow the bug you created. :smiley:

Cheers,
Kristoffer

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.