gpt4 book ai didi

c++ - 引用抽象类的类的 copy-and-swap 习语

转载 作者:搜寻专家 更新时间:2023-10-31 00:44:24 27 4
gpt4 key购买 nike

我正在尝试实现 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 解决方案,请告诉我,因为我最近开始使用它。

最佳答案

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

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

关于c++ - 引用抽象类的类的 copy-and-swap 习语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com