【问题标题】:Copy-and-Swap idiom for class with references to abstract classes引用抽象类的类的复制和交换习语
【发布时间】:2012-02-09 01:26:45
【问题描述】:

我正在尝试为我的班级实现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 );
}

这是成语中的 Swap 函数,m_Variables 确实是对抽象类的引用。交换那种参考是不可能的吗?如果有对此的 Boost 解决方案,请告诉我,因为我最近开始使用它。

【问题讨论】:

  • stackoverflow.com/questions/15463321/…看到一个神丑的解决方案
  • 我见过更丑陋的东西。但是你为什么要这样做而不是仅仅使用指针呢? (必须是“不可触碰的”遗留代码或第三方代码)。不过读起来很有趣。

标签: c++ reference abstract-class copy-and-swap


【解决方案1】:

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

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

【讨论】:

  • 那么...如果一个类有引用成员,operator=不能正确实现?
  • C++11 也是这样吗?
  • @dario_ramos:是的; C++11 也不允许你重新分配引用。
  • 您也可以使用 pimpl。将您的引用放入 pimpl 并交换 pimpl。
  • C++ 标准化委员会计划在 C++2x 中通过添加诸如 int&amp;&amp;&amp; 的 s 值引用来解决此问题;-)
猜你喜欢
  • 2014-06-23
  • 2015-11-28
  • 2011-10-28
  • 2019-03-25
  • 2015-07-21
  • 2023-03-23
  • 1970-01-01
  • 2011-10-10
  • 2020-05-27
相关资源
最近更新 更多