I've searched on internet but i can't find any resources on the behavior of the default destructor on reference.
Example:
struct A{
int &a;
A(int&i): a(i){}
}
void f(){
int* i = new int;
A* a = new A(*i);
delete a; // is i been destroyed?
}
In both cases, where i can find resources about this? Or can someone please explain me how it behaves?
References are not objects. They don't have destructors. They have lifetimes. Objects have lifetime too, as any other type in C++.
The difference is that, when the lifetime of an object ends, its destructor is called. But when the lifetime of any other type ends, their resources are simply freed.
In case of a reference, the resource they hold is the memory address pointing to another value. Not the value itself. So when it gets freed, the value stays the same. The stored memory address is what's getting released, not the value.
When you use new/delete, you are manually stating when a lifetime starts (on new) and when it ends (on delete).
In the case of your example, your lifetimes X and Y, would be the following:
struct A{
int &a;
A(int&i): a(i){}
}
void f(){
int* i = new int; // ----------------------------------|X
A* a = new A(i); // -------------------|Y |X
delete a; // is i been destroyed? // --|Y |X
} // |X
// |X...
As you can see, the lifetime of X continues forever, as you didn't delete it manually but you created it with new. This means that the value that is hold in i
, would still be valid after the line where you delete a
.
PD: You should have written new A(*i)
instead, otherwise you would get a compiler error.