Quando si dispone di:
B b = a->getB();
viene creato un nuovo oggetto di tipo B
da un riferimento all'istanza esistente di B
(B&
). Non è lo B::operator=
chiamato qui ma il costruttore di copie .
Ogni classe ha un costruttore di copie (se non lo si specifica esplicitamente, il compilatore ne fornirà uno). Accetta un singolo argomento che è un riferimento alla stessa classe. Non hai messo costruttore di copia nel codice sopra quindi immagino che il compilatore ha generato uno per te:
class B
{
public:
B(B& other)
{
// memberwise copy (shallow copy)
};
};
Così A::getB()
tornato un riferimento al membro A::b
e questo riferimento è stato passato come argomento a B::B(B&)
.
void func()
{
A *a = new A(); // Instance of A is created on the heap;
// (pointer a is a local variable and is on the stack though!)
// A::b is object of type B and it is on the heap as well
B b = a->getB(); // Instance of class B is created on the stack (local variable)
.....
delete a; // deleting A from the heap:
// A::~A is called which calls B::~B (of its member b)
} // a and b go out of the scope; b is an object => B::~B is called
fonte
2012-05-29 15:30:48
L'oggetto b è ancora locale alla funzione. –