2012-01-12 62 views
2

我试图为我的类实现Copy-and-Swap Idiom,因为我需要实现operator=,并且由于它具有引用成员,并且引用只能分配一次,我认为上述成语是一个有效的解决方法。复制交换成语类与抽象类的引用

但现在我越来越生成错误:

>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 – 2013-03-17 16:42:20

+0

我见过方式更丑的东西。但是,为什么你会这样做,而不是仅仅使用一个指针? (必须是“不可触摸的”传统或第三方代码)。尽管如此,有趣的阅读。 – 2013-03-18 15:39:49

回答

5

引用不能被重新分配。 swap将尝试交换被引用的对象(如果使用默认的std::swap,则通过临时对象分配它们)。由于它们引用抽象基类,因此无法创建临时文件,因此失败。

如果您想要一个可重新分配的引用,请改为使用指针。

+0

那么......如果一个类有引用成员,'operator ='不能正确实现? – 2012-01-12 19:17:46

+0

@dario_ramos:没错。 – 2012-01-12 19:19:38

+0

这对C++ 11来说是否也是如此? – 2012-01-12 19:21:02