Is it the right approach to explicitly define the missing copy constructor, move constructor, copy assignment operator and move assignment operator so

  • Thread starter Thread starter bhavya internship
  • Start date Start date
B

bhavya internship

Guest
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:

To resolve sonarqube 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?

Continue reading...
 
Back
Top