2

I'm trying to implement the Copy-and-Swap Idiom for my class, because I need to implement operator=, and since it has reference members, and references can only be assigned once, I thought that the aforementioned idiom was a valid workaround.

But now I'm getting a build error:

>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>          ]

It points me here:

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

This is the Swap function from the idiom, and m_Variables is indeed a reference to an abstract class. Is it impossible to swap that kind of references? If there is a Boost solution for this, please tell me since I recently started using it.

Community
  • 1
  • 1
dario_ramos
  • 6,536
  • 7
  • 50
  • 104
  • 1
    See a god ugly solution in http://stackoverflow.com/questions/15463321/a-way-to-swap-two-references-in-c – the swine Mar 17 '13 at 16:42
  • I've seen way uglier stuff. But why would you do that instead of just using a pointer? (must be "untouchable" legacy or third party code). An interesting read nevertheless. – dario_ramos Mar 18 '13 at 15:39

1 Answers1

5

References can't be swapped any more than they can be reassigned. swap will attempt to swap the objects being referred to (by assigning them via a temporary object, if the default std::swap is used). Since they refer to an abstract base class, then this fails since the temporary can't be created.

If you want a reassignable reference, then use a pointer instead.

Mike Seymour
  • 235,407
  • 25
  • 414
  • 617