如何在C+中“返回一個對象”?我知道標題聽起來很熟悉,因為有很多類似的問題,但是我要求問題的另一個方面(我知道堆棧上的東西和堆中的東西之間的區別)。在Java中,我總是可以返回對“本地”對象的引用public Thing calculateThing() {
Thing thing = new Thing();
// do calculations and modify thing
return thing;}在C+中,為了做類似的事情,我有兩個選項(1)每當需要“返回”對象時,我都可以使用引用void calculateThing(Thing& thing) {
// do calculations and modify thing}然后像這樣使用它Thing thing;calculateThing(thing);(2)或者我可以返回指向動態分配對象的指針Thing* calculateThing() {
Thing* thing(new Thing());
// do calculations and modify thing
return thing;}然后像這樣使用它Thing* thing = calculateThing();delete thing;使用第一種方法,我不必手動釋放內存,但對我來說,這會使代碼難以閱讀。第二種方法的問題是,我必須記住delete thing;看起來不太好。我不想返回復制的值,因為它效率很低(我認為),下面是問題是否有第三種解決方案(不需要復制值)?如果我堅持第一個解決方案,有什么問題嗎?何時以及為什么要使用第二個解決方案?
3 回答
翻過高山走不出你
TA貢獻1875條經驗 獲得超3個贊
我不想返回復制的值,因為它效率低下
料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
Thing calculateThing() {
Thing thing;
// do calculations and modify thing
return thing;}
當年話下
TA貢獻1890條經驗 獲得超9個贊
Thing calculateThing() {
Thing thing();
// do calculations and modify thing
return thing;}Thing(const Thing& aThing) {}更新
- 3 回答
- 0 關注
- 564 瀏覽
添加回答
舉報
0/150
提交
取消
