関数オブジェクトでの継承に関する質問があります。派生クラスの関数呼び出し演算子を呼び出すときにポインタを避ける
これはスタックオーバーフローでgazzilionの時間を尋ねられているはずですが、同様の文言で膨大な数の質問があれば、私は何かを見つけるのがほぼ不可能になります。
私は基本抽象クラスがあるとします。私は由来している様々なファンクタに文字列をマップするためにstd::map
を使用したい
class Plus : public BinaryOperation
{
public:
virtual int operator()(int a, int b)
{
return a + b;
};
};
class Minus : public BinaryOperation
{
public:
virtual int operator()(int a, int b)
{
return a - b;
};
};
:二つの新しいクラスが派生
class BinaryOperation
{
public:
virtual int operator()(int a, int b) = 0;
};
、そこからの同じクラス:
私の最初のアプローチは
std::map<std::string, BinaryOperation> operator_map;
operator_map["+"] = Plus();
operator_map["-"] = Minus();
operator_map["-"](5, 2);
抽象クラスをインスタンス化できないため、明らかにこれは機能しませんでした。私は、基本クラスへのポインタを使用する場合は
、
(私たちはを手動delete
オブジェクトを持っている)それだけで正常に動作しますが、それはclumsier見て、私たちは
new
にオブジェクトを持っているので、メモリリークにそれが起こりやすくなり、その
std::map<std::string, BinaryOperation*> operator_map;
operator_map["+"] = new Plus();
operator_map["-"] = new Minus();
std::cout << (*operator_map["-"])(5, 2)
RAIIの利点を犠牲にすることなくこの機能を達成するための好ましい方法は何ですか?
あなたはスマートポインタを使用するときにあまりにも多くのポインタを心配する必要はありません。) – chris
まあ、私は広範囲にそれらを使用し、知っています。私はちょうど彼らが何か明らかにそう簡単に必要でないことを願っています:) – Tibor