Dej*_*jan 7 c++ operator-overloading move-semantics c++17
我正在尝试第一次实施五规则。在阅读了大量关于最佳实践的建议后,我最终得到了一个解决方案,其中复制/移动赋值运算符似乎存在一些冲突。
这是我的代码。
#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;
}
Run Code Online (Sandbox Code Playgroud)
我从这里得到的大部分建议,我实现了复制分配operator=以按值接受参数。我认为这可能是一个问题,但我不明白为什么。
此外,如果有人指出我的复制/移动构造函数/分配是否以正确的方式实施,我将不胜感激。
你应该有:
TUndirectedG& operator=(const TUndirectedG&);
TUndirectedG& operator=(TUndirectedG&&);
Run Code Online (Sandbox Code Playgroud)
或者
TUndirectedG& operator=(TUndirectedG);
Run Code Online (Sandbox Code Playgroud)
两者都有
TUndirectedG& operator=(TUndirectedG); // Lead to ambiguous call
TUndirectedG& operator=(TUndirectedG&&); // Lead to ambiguous call
Run Code Online (Sandbox Code Playgroud)
会导致与右值不明确的调用。