gpt4 book ai didi

c++:运算符=在实现 move 赋值时不明确

转载 作者:太空狗 更新时间:2023-10-29 22:55:01 24 4
gpt4 key购买 nike

我第一次尝试实现五规则。在阅读了很多关于最佳实践的建议之后,我最终得到了一个解决方案,其中复制/move 赋值运算符似乎存在一些冲突。

这是我的代码。

#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= 以通过 value 接受参数。我认为这可能是个问题,但我不明白为什么。

此外,如果有人指出我的复制/move 构造函数/赋值是否以正确的方式实现,我将不胜感激。

最佳答案

你应该:

TUndirectedG& operator=(const TUndirectedG&);
TUndirectedG& operator=(TUndirectedG&&);

TUndirectedG& operator=(TUndirectedG);

两者兼而有之

TUndirectedG& operator=(TUndirectedG);   // Lead to ambiguous call
TUndirectedG& operator=(TUndirectedG&&); // Lead to ambiguous call

会导致带有右值的模棱两可的调用。

关于c++:运算符=在实现 move 赋值时不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652653/

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