【发布时间】:2019-05-08 05:22:18
【问题描述】:
我第一次尝试实施五规则。在阅读了很多关于最佳实践的建议后,我最终找到了一个解决方案,其中复制/移动赋值运算符似乎存在一些冲突。
这是我的代码。
#include <vector>
#include <memory>
template<class T> class DirectedGraph {
public:
std::vector<T> nodes;
DirectedGraph() {}
DirectedGraph(std::size_t n) : nodes(n, T()) {}
// ... Additional methods ....
};
template<class T>
DirectedGraph<T> Clone(DirectedGraph<T> graph) {
auto clone = DirectedGraph<T>();
clone.nodes = graph.nodes;
return clone;
}
template<class T> class UndirectedGraph
{
using TDirectedG = DirectedGraph<T>;
using TUndirectedG = UndirectedGraph<T>;
std::size_t numberOfEdges;
std::unique_ptr<TDirectedG> directedGraph;
public:
UndirectedGraph(std::size_t n)
: directedGraph(std::make_unique<TDirectedG>(n))
, numberOfEdges(0) {}
UndirectedGraph(TUndirectedG&& other) {
this->numberOfEdges = other.numberOfEdges;
this->directedGraph = std::move(other.directedGraph);
}
UndirectedGraph(const TUndirectedG& other) {
this->numberOfEdges = other.numberOfEdges;
this->directedGraph = std::make_unique<TDirectedG>
(Clone<T>(*other.directedGraph));
}
friend void swap(TUndirectedG& first, TUndirectedG& second) {
using std::swap;
swap(first.numberOfEdges, second.numberOfEdges);
swap(first.directedGraph, second.directedGraph);
}
TUndirectedG& operator=(TUndirectedG other) {
swap(*this, other);
return *this;
}
TUndirectedG& operator=(TUndirectedG&& other) {
swap(*this, other);
return *this;
}
~UndirectedGraph() {}
};
int main()
{
UndirectedGraph<int> graph(10);
auto copyGraph = UndirectedGraph<int>(graph);
auto newGraph = UndirectedGraph<int>(3);
newGraph = graph; // This works.
newGraph = std::move(graph); // Error here!!!
return 0;
}
我从here 获得的大部分建议,我实现了复制分配operator= 以通过值 接受参数。我认为这可能是个问题,但我不明白为什么。
此外,如果有人指出我的复制/移动 ctor/分配是否以正确的方式实现,我将不胜感激。
【问题讨论】:
-
使用 copy-and-swap 习语,您不需要额外的移动赋值运算符
-
copy-and-swap 涵盖了 const& 和 &&。要么进行复制和交换(只有一个重载按值获取参数),要么为 operator= 实现 const& 和 && 重载
-
既然您决定(为什么?)按值进行赋值,参数可以通过移动构造函数传递。 (按值赋值只会导致不必要的复制。不要这样做。)
-
@molbdnilo 是个成语,是抄还是搬要看用法
-
@Dejan 它是“四个半”,因为按值接受参数的赋值运算符可用于复制和移动赋值。这是因为参数表达式可以是左值或右值,并且参数将从该参数表达式移动或复制构造。因此,您不需要提供复制赋值运算符或移动赋值运算符,因为按值接受参数的一个允许您通过移动或复制构造来构造该参数本身。一旦构造了参数,它的内容就会与隐式对象交换
标签: c++ operator-overloading c++17 move-semantics