2016-03-25 6 views
1

イム学習C++多型を設定し、先生は、私たちは派生クラスで基本クラスにnumber_tを使用して計算をやってみたかった:real_t、など。メモリリークが今C++

integer_t多型なし

私はこれに非常によく似operator+を移植します:

real_t real_t::operator+(const integer_t& number) const 
{ 
    /* Sum operations of (real_t + integer_t) */ 
    /* Create a new real with the result of the sum and return it */ 
    return real_t(...); 
} 

この方法は、2つの数の合計があった場合、それはINVOある数字の値を変更することが文句を言いません忘れたが新しいものを返す。

しかし、多型と、私はポインタを返す必要が、例えば、これは私が何をするかです:

number_t* real_t::operator+(const number_t* number) const 
{ 
    /* Sum operations of two numbers which will output a real_t (for example)*/ 
    /* Create a new real with the result of the sum and return it */ 
    /* The return value will be of the type of the biggest set, for example: 
     integer + real = real 
     complex + real = complex 
    */ 
    return new real_t(...); 
} 

問題ここでは、文句を言わないnewオペレータによって作成されたメモリが解放されています。この操作で:

d = (a + b) + c 

合計(a+b)によって割り当てられたメモリが解放され文句を言わないことはありませんこと。

これにはより良いアプローチがありますか?

+1

"しかし、多型ではポインタを返す必要があります..."いいえ;あなたはそうしない。ここでも値でnumber_tを返さなければならない方がよいでしょう。 (a + b)はnumber_tでなければなりません。 – Loreto

+0

'number_t real_t :: operator +(...){... return real_t(...);}を実行するのは問題ありません。 } '?私はそれがポインター、おかげで働いたと思った。 – Ediolot

+0

いいえ、それはokではありません。オブジェクトを[スライス](http://stackoverflow.com/q/274626/3425536)します。 'real_t'を返すなら、戻り値の型を' real_t'と宣言してみませんか?彼らが望むなら、ユーザーは 'number_t'としてそれを扱うことができます。 – emlai

答えて

0

戻るスマートポインタ:

unique_ptr<number_t> real_t::operator+(const number_t& number) const 
{ 
    /* Sum operations of two numbers which will output a real_t (for example)*/ 
    /* Create a new real with the result of the sum and return it */ 
    return make_unique<real_t>(...); 
} 

今中間値が自動的に解放されます。