[英]Returning a new Object by reference
來自Java的更多背景,我想知道如何通過引用返回新對象。 我希望Fraction
類是不可變的,以便每個操作都返回一個帶有操作結果的新對象。
這是我的Java代碼:
class Fraction {
int numerator;
int denominator;
// Constructor
Fraction multiply(Fraction other) {
return new Fraction(other.numerator * this.numerator,
other.denominator * this.denominator);
}
}
但是,如果我在C ++中這樣做,則會造成內存泄漏,因為我無法清理初始化的Fraction
對象,因為我只有對該對象的引用。 那么,如何用C ++處理呢?
class Fraction {
private:
int32_t numerator;
int32_t denominator;
public:
Fraction(int32_t numerator, int32_t denominator) {
this->numerator = numerator;
this->denominator = denominator;
}
Fraction& operator*(Fraction& other) {
auto numerator = other.numerator * this->numerator;
auto denominator = other.denominator * this.denominator;
return *(new Fraction(numerator, denominator))
}
};
在C ++中,您可以控制要放置對象的位置。 您可以根據需要選擇堆棧/堆。
我現在不想讓您感到困惑,但是如果您想對對象在內存中的位置進行更多控制,則可以查找“ placement new”的使用。
我不是JAVA方面的專家,但是上次檢查時,您必須使用new來在Java中分配對象。
我認為這已經在這里很好地解釋過。何時使用/不使用c ++中的new。
歡迎來到C ++的世界
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.