我剛剛發現,你可以在C++中做到這一點:如何刪除堆中未存儲到變量指針的對象?
class Line
{
public:
Line(int x) : _length(x) {}
int GetLength() { return _length; }
private:
int _length;
};
int main()
{
Line* line = new Line(3); // instead of doing this
std::cout << line->GetLength();
std::cout << (new Line(5))->GetLength(); // you can instantiate the object directly without storing it in a pointer
}
現在的問題是,代碼,最後一行後,確實有長度= 5的對象獲取堆中立即刪除?如果不是,我們如何刪除它,因爲我們不能使用
delete line;
像第一個對象的長度= 3。
你已經學會了如何泄漏內存 – AndyG
避免直接使用'new',並且意外地做到這一點變得相當困難。 – chris