bone_appettit
bone_appettit

Reputation: 125

Why destructor is calling?

I have a simple code.

#include <iostream>

struct BABE
{
    std::string* babe = nullptr;

    BABE(const char* str)
    {
        babe = new std::string(str);
    }
    ~BABE()
    {
        delete babe;
    }
};

int main()
{
    BABE bomb = "hello";
    bomb = "world";
    
    system("pause");
    return 0;
}

When Im trying to

bomb = "world";

it assign well, but then destructor is calling.

Why is it happening?


bbb

Upvotes: 0

Views: 72

Answers (1)

Slava
Slava

Reputation: 44238

Why is it happening?

Because in this line:

bomb = "world";

To assign a const char * to your class, a temporary of struct BABE is created, that temporary is assigned to bomb (using the compiler-generated assignment operator), and then that temporary is destructed.

As you violated the Rule of 3/5/0, the assignment leads to a disaster - a memory leak and a double-deletion of the same pointer.

Upvotes: 4

Related Questions