兩個你的例子是合法的。有其他人已經建議的更好的方法,但原則上你的代碼是好的。我試圖添加一些評論來解釋發生了什麼。希望澄清它。
而且「不 - 你不需要爲b保留內存」。編譯器會爲你處理它。
你的第一示例
A* dum()
{
A* a; // The compiler reserves memory for holding
// the pointer a on the stack.
a = new A(); // On run time you reserve memory on the heap
// for holding an instance of class A.
doSomethingOnA(a); // Some function call where you pass the pointer
return a; // Return the pointer. This will also release
// the stack memory used for holding the pointer a.
}
在另一功能:
void func()
{
A* b; // The compiler reserves memory for holding
// the pointer b on the stack.
b = dum(); // The value of the pointer b is changed
// so it points to the instance of class A
// which is in the heap. The pointer b is
// still on the stack.
// ... more code
delete b; // Delete b to free the heap memory
// (and call the class A destructor).
return; // This will release
// the stack memory used for holding the pointer b.
}
你的第二示例
的原理是相同的。
和「無 - 你不需要新的功能達姆(..)內 事實上,這將是一個錯誤
bool dum(A* a)
{
// As this function has no local variable, no stack
// memory will be needed for holding variables.
// A* a = new A() -- Is this needed? NO - it would be a bug
doSomethingOnA(a);
return 1;
}
void func()
{
A* b; // The compiler reserves memory for holding
// the pointer b on the stack.
b = new A(); // On run time you reserve memory on the heap
// for holding an instance of class A.
// The value of the pointer b is changed
// so it points to the instance of class A
// which is in the heap. The pointer b is
// still on the stack.
dum(b); // Just a function call
// ... more code
delete b; // Delete b to free the heap memory
// (and call the class A destructor).
return; // This will release
// the stack memory used for holding the pointer b.
}
注: 編譯器可以優化使用棧。因此,在函數內部的局部變量是在寄存器中完全保留,爲此並不需要在所有的內存。
你說的「指定內存」是什麼意思? – Borgleader
沒有,'B'是''從達姆彈了'( )','因爲A'被指向的數據,和'B'將指向相同的地址然後'A' – Eun
@Borgleader - 我的意思是perfoming b =新A() –