2012-01-12 12 views
2

operator=を実装する必要があるため、Copy-and-Swap Idiomを実装しようとしています。参照メンバを持ち、参照を1回しか割り当てることができないため、私は、前述のイディオムが有効な回避策であると考えました。抽象クラスへの参照を持つクラスのコピー&スワップイディオム

しかし、今、私はビルドエラーになっています:

>c:\Program Files\Microsoft Visual Studio 10.0\VC\include\utility(102): error C2259: 'IVariables' : cannot instantiate abstract class 
1>   due to following members: 
1>   'IVariables::~IVariables(void)' : is abstract 
1>   d:\svn.dra.workingcopy\serialport\IVariables.h(6) : see declaration of 'IVariables::~IVariables' 
1>   'std::string &IVariables::operator [](const std::string &)' : is abstract 
1>   d:\svn.dra.workingcopy\serialport\IVariables.h(7) : see declaration of 'IVariables::operator []' 
1>   'unsigned int IVariables::getVariableLength(const std::string &) const' : is abstract 
1>   d:\svn.dra.workingcopy\serialport\IVariables.h(8) : see declaration of 'IVariables::getVariableLength' 
1>   Message.cpp(32) : see reference to function template instantiation 'void std::swap<IVariables>(_Ty &,_Ty &)' being compiled 
1>   with 
1>   [ 
1>    _Ty=IVariables 
1>   ] 

をそれはここに私を指す:

void Swap(CMessage& a, CMessage& b){ 
    using std::swap; 
    swap(a.m_bIgnoreIncoming, b.m_bIgnoreIncoming); 
    swap(a.m_Variables, b.m_Variables); 
} 

これはイディオムからスワップ機能である、とm_Variablesが実際に参照されます抽象クラス。そのような参照を交換することは不可能ですか?このためのBoostソリューションがある場合は、最近使用し始めてから教えてください。

+1

醜い解決策はhttp://stackoverflow.com/questions/15463321/a-way-to-swap-two-references-in-c –

+0

私は醜い方法を見てきました。しかし、ポインタを使うのではなく、なぜあなたはそれをやるでしょうか? (「アンタッチャブル」のレガシーコードまたは第三者コードでなければならない)。それにもかかわらず、面白い読書。 –

答えて

5

参照を再割り当てすることはできません。 swapは、参照されているオブジェクトをスワップしようとします(デフォルトオブジェクトstd::swapが使用されている場合は、それらを一時オブジェクト経由で割り当てます)。それらは抽象基本クラスを参照するため、一時的な作成ができないため失敗します。

再割り当て可能な参照が必要な場合は、代わりにポインタを使用します。

+0

だから...クラスに参照メンバがある場合、 'operator ='は正しく実装できません。 –

+0

@dario_ramos:それは正しいです。 –

+0

これはC++ 11でも同様ですか? –

関連する問題