gpt4 book ai didi

c++ - 当存在要复制的值数组时,在 C++ 中重载 = 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:10:16 25 4
gpt4 key购买 nike

我对 C++ 有点陌生,所以我想这是一个非常基本的问题。

假设我有这个类:

// file Graph.h
class Graph {
public:
Graph(int N); // contructor
~Graph(); // destructor
Graph& operator=(Graph other);
private:
int * M;
int N;
};

// file Graph.cpp
Graph :: Graph(int size) {
M = new int [size];
N = size;
}

Graph :: ~Graph() {
delete [] M;
}

我想创建一个赋值运算符,它将复制数组 M[] 的内容,但在复制后更改它时不会覆盖它(我认为这是通过不复制实际指针而只复制内容来完成的,不知道我是否正确)。这是我试过的:

Graph& Graph::operator=(Graph other) {
int i;
N = other.N;
M = new int [N];
for (i = 0; i < N; i++)
M[i] = other.M[i];
return *this;
}

这是正确的吗?还有其他方法吗?

编辑:我忘记了一个重要的问题。为什么我必须声明它像 Graph& operator=(Graph other); 而不仅仅是: Graph operator=(Graph other); 这是我书中写的(C++:完整引用,第 2 版,Herbert Schildt,第 355-357 页)?

最佳答案

规范的方法是使用 std::vector<int>避免自己管理内存。不过对于练习,做你想做的事情的正确方法是:

#include <algorithm>

class Graph
{
public:
Graph(size_t n) { data_ = new int[n](); size_ = n; }

Graph(Graph const& g)
{
data_ = new int(g.size_);
size_ = g.size_;
std::copy(g.data_, g.data_ + g.size_, data_);
}

~Graph() { delete[] data_; }

void swap(Graph& g) throw()
{
std::swap(data_, g.data_);
std::swap(size_, g.size_);
}

Graph& operator=(Graph g) { g.swap(*this); return *this; }

private:
int* data_;
size_t size_;
};

Google“copy and swap idiom”以了解代码背后的基本原理。请注意,您的赋值运算符会泄漏内存(原始数组被覆盖但从未被删除),如果分配失败,您最终会得到一个损坏的对象。此外,x = x不会做预期做的事。这三个陷阱很常见,以 copy-and-swap 风格编写赋值运算符可以避免它们。

编辑:对于您的其他问题,返回引用允许您链接分配,例如 a = b = c ,这对内置类型有效。它可能是也可能不是您想要的(通常是)。

关于c++ - 当存在要复制的值数组时,在 C++ 中重载 = 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267327/

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