根据什么是拷贝并交换惯用法和如何为我的类提供交换函数,我尝试实现了交换函数,并使用了后一篇回答的第二个选项(使用调用成员函数的自由函数),而非前者的直接友元自由函数。
但是以下代码无法通过编译。
我知道复制和交换习惯用法在这里有些过度,但它也允许通过复制构造函数(1)对内部状态强制执行一些约束(一个更具体的例子是保持分数为最简形式)。不幸的是,这并不能编译,因为编译器只看到Bar::swap成员函数作为(2)的唯一候选项。我该使用友元非成员函数方法吗?
编辑:前往我的答案查看我最终采用的方案,感谢本问题中所有答案和评论。
但是以下代码无法通过编译。
#include <iostream>
// Uncommenting the following two lines won't change the state of affairs
// class Bar;
// void swap(Bar &, Bar &);
class Bar {
public:
Bar(unsigned int bottles=0) : bottles(bottles) { enforce(); } // (1)
Bar(Bar const & b) : bottles(b.bottles) { enforce(); } // (1)
Bar & operator=(Bar const & b) {
// bottles = b.bottles;
// enforce();
// Copy and swap idiom (maybe overkill in this example)
Bar tmp(b); // but apart from resource management it allows (1)
// to enforce a constraint on the internal state
swap(*this, tmp); // Can't see the swap non-member function (2)
return *this;
}
void swap(Bar & that) {
using std::swap;
swap(bottles, that.bottles);
}
friend std::ostream & operator<<(std::ostream & out, Bar const & b) {
out << b.bottles << " bottles";
return out;
}
private:
unsigned int bottles;
void enforce() { bottles /=2; bottles *= 2; } // (1) -- Ensure the number of bottles is even
};
void swap(Bar & man, Bar & woman) { // (2)
man.swap(woman);
}
int main () {
Bar man (5);
Bar woman;
std::cout << "Before -> m: " << man << " / w: " << woman << std::endl;
swap(man, woman);
std::cout << "After -> m: " << man << " / w: " << woman << std::endl;
return 0;
}
我知道复制和交换习惯用法在这里有些过度,但它也允许通过复制构造函数(1)对内部状态强制执行一些约束(一个更具体的例子是保持分数为最简形式)。不幸的是,这并不能编译,因为编译器只看到Bar::swap成员函数作为(2)的唯一候选项。我该使用友元非成员函数方法吗?
编辑:前往我的答案查看我最终采用的方案,感谢本问题中所有答案和评论。
this->swap(other)
? - Yakk - Adam Nevraumont