I am trying to implement a rule of five for the first time. After reading a lot of recommendation about best practices, I end up with a solution where copy/move assignment operators seem to be in some conflict.
Here is my code.
#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;
}
Most of the recommendations I took from here, and I implemented copy assignment operator=
to accept parameter by value. I think this might be a problem, but I don't understand why.
Additionally, I would highly appreciate if someone point out whether or not my copy/move ctor/assignments are implemented in the correct way.
newGraph = std::move(graph);
where I should invoke move assignment operator. I don't understand why I don't need additional move-assignment op with copy swap idieom. Without it I will call a regular assignment operator (which is probably not a good choice). – Dreeoperator=
is either copy- or move-constructed – Furtek