Is it the right approach to explicitly define the missing copy constructor, move constructor, copy assignment operator and move assignment operator to resolve the sonarqube C++ error

Hi all,

I have the below code

In .h file
class ClassA{

private:
ClassA* pClassAHandler;
public:
~ClassB(void);
}

In .cpp file

ClassB::~ClassB()
{
if(nullptr != pClassAHandler)
{
delete pClassAHandler;
pClassAHandler = nullptr;
}
}

With that I am getting the below error:

Explicitly define the missing copy constructor, move constructor, copy assignment operator and move assignment operator so that they will not be implicitly provided.

I am following rule of 5 and providing the below special functions (copy constructor, move constructor, copy assignment operator and move assignment operator):

ClassB::ClassB(const ClassB &other) {
pClassAHandler = new ClassA(other.pClassAHandler->value);
}

ClassB::ClassB& operator=(const ClassB& other) {
int val = other.pClassAHandler->value;
delete pClassAHandler;
pClassAHandler = new ClassA(val);
return *this;
}

ClassB::ClassB(ClassB &&fp) noexcept {
pClassAHandler = fp.pClassAHandler;
fp.pClassAHandler = nullptr;
}

ClassB::ClassB const & operator=(ClassB &&fp) {
ClassB temp(std::move(fp));
std::swap(temp.pClassAHandler, pClassAHandler);
return *this;
}

Do we need to define all these functions like as shown above?

And also is it the right approach to define those functions? And will i get any other issues if i use those functions?

Please help me on this?

Hello @bhavya_intern.

Thanks for contacting us.
In the extract you give, it is not possible to fully get the intention and the architecture of your code but a few comments might help:

  • The idea of the rule is that in your classB, you are doing something special in the destructor. In your case it is because you are deleting some resource. So, it would make sense to have the 5 special functions being consistent about the way you are manageing the resource. That would mean to define them all. In your extract, it is not clear how the pClassAHandler is initialized.
  • You probably have other issues reported as you are using new and delete. Especially in your case, I would have a look to https://en.cppreference.com/w/cpp/memory/unique_ptr. By using those, you can probably simplify the resource management a lot and lower risks of dangling and null pointers.
  • Another hint.If they are not required or if the default implementation is fine, consider using = default and = delete for your special functions as explained for the default constructor there. https://en.cppreference.com/w/cpp/language/default_constructor.

I hope this will help to better understand the spirit of this rule and how to best comply.

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