:
B b = a->getB();
B
類型的新對象被創建從對B
(B&
)的現有實例的引用。它不是B::operator=
這裏被稱爲複製構造函數。
每個類都有一個拷貝構造函數(如果你沒有明確地添加它,編譯器會爲你提供一個)。它接受一個參數,它是對同一個類的引用。你還沒有把拷貝構造函數在上面的代碼,所以我認爲編譯器產生了一個給你:
class B
{
public:
B(B& other)
{
// memberwise copy (shallow copy)
};
};
所以A::getB()
退還給會員A::b
參考,了此引用作爲參數傳遞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
您的b對象仍然是函數的本地對象。 –