Skip to content

Instantly share code, notes, and snippets.

@Loki-Astari
Last active June 2, 2021 08:58
Show Gist options
  • Save Loki-Astari/456ba81de186f923d709129f2968bb11 to your computer and use it in GitHub Desktop.
Save Loki-Astari/456ba81de186f923d709129f2968bb11 to your computer and use it in GitHub Desktop.
struct der
{
private: // No resources :-(
int *p=new int[4]; // This is a resource.
// If you don't do anything it will leak.
public:
};
struct derWithDestructorOnly: public base
{
private:
int *p=new int[4];
public:
~derWithDestructorOnly() {
delete [] p; // When the object is destroyed you need to relase the memory.
}
// This is still broken as it does not implement the rule of three see below.
};
struct derWithRuleOfThree: public base
{
private:
int *p=new int[4];
public:
~derWithRuleOfThree() {
delete [] p; // When the object is destroyed you need to relase the memory.
}
derWithRuleOfThree(derWithRuleOfThree const& rhs) {
for(int loop = 0; loop < 4; ++loop) [
p[loop] = rhs.[loop];
}
}
derWithRuleOfThree& operator=(derWithRuleOfThree const& rhs) {
for(int loop = 0; loop < 4; ++loop) [
p[loop] = rhs.[loop];
}
return *this;
}
};
int test1()
{
der derObject;
}
// Object out of scope.
// the destructor did not clean it up you leaked 4 bytes of memory.
int test2()
{
derWithDestructorOnly derObject;
}
// Worked correctly the memory was correctly released by the destructor of the object.
int test3()
{
derWithDestructorOnly derObjectOne; // derObjectOne.p = 0x456780
derWithDestructorOnly derObjectTwo; // derObjectOne.p = 0x4567A0
derObjectTwo = derObjectOne;
// Whoops.
// The rule of three was not implemented.
// derObjectTwo.p == derObjectOne.p == 0x456780
// You have lost all reference to 0x4567A0 (so this memory has now leaked.
}
// The destructor of derObjectTwo is called first.
// It calls delete [] 0x456780 thats fine.
// The destructor of derObjectOne is called next.
// It calls delete [] 0x456780 thats A PROBLEM as you just deleted it.
int test4()
{
derWithRuleOfThree derObjectOne; // derObjectOne.p = 0x456780
derWithRuleOfThree derObjectTwo; // derObjectOne.p = 0x4567A0
derObjectTwo = derObjectOne;
// Everything works.
}
@abhisekmane98
Copy link

abhisekmane98 commented Jun 2, 2021

But I have one Question why memory will not leak in derWithRuleOfThree but leak in derWithDestructorOnly. As ultimately in derWithRuleOfThree we are copying derObjectOne to derObjectTwo. so ptr variable p in derObjectTwo get address of variable which pointed by ptr varible p of derObjectOne. so it's obivious that memory will leak. https://stackoverflow.com/a/4172724/11862989 in his answer fredoverflow(user with 237k Rep) said regarding Rule of three " "Unfortunately, this "rule" is not enforced by the C++ standard or any compiler I am aware of.".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment