【问题标题】:Copy assignment explanation (C++)复制赋值说明(C++)
【发布时间】:2018-01-06 16:25:09
【问题描述】:

Vector类的复制赋值和移动赋值代码如下:

//Copy assignment

Vector& Vector::operator = (const Vector& other)
        {
            double* p = new double[other.size];
            copy(other.elem,other.elem + other.size,elem);
            delete[] elem;
            elem = p;
            size = other.size;
            return *this
        }

这是我对复制分配的理解:

double* p = new double[other.size]; 

- 表示我们为新向量分配新空间

copy(other.elem,other.elem + other.size,elem);

-我们将other向量的所有元素(从第一个元素other.elem到最后一个元素other.elem + other.size)复制到空间p?

delete[] elem;

-我们释放旧空间,因为我们将用新空间替换它

elem = p;
size = other.size;
return *this

- 我们用新参数替换参数并返回它们

我的理解正确吗?

我不明白(或者至少现在我的大脑无法接受),如果我们释放旧空间,为什么可以为其分配新元素?

【问题讨论】:

  • 关于copy调用,你的理解是错误的。你看到p在通话中的任何地方使用了吗?
  • 我还建议您查看this canonical implementation of the copy-assignment operator。请密切注意该函数中的第一条语句(if)。由于你做事的顺序,你绕过了这个问题,但如果你将对象分配给它自己,你仍然可以做你不必做的操作。
  • @Someprogrammerdude 用于分配 elem = p
  • 是的,但您不会从另一个复制p。你复制到elem。如果this->sz < other.sz,这可能会导致一些大问题。
  • @Someprogrammerdude 这段代码实际上来自使用 c++ Stroustrup 的编程原理和实践。正如你所理解的,我不明白。如果有时间,能否一步步解释每一行的意思?

标签: c++


【解决方案1】:

问题在于

double* p = new double[other.size];

您为新的“数组”分配内存,并让p 指向它。然后用

 copy(other.elem,other.elem + other.size,elem);

您复制到 “数组”,因为目标是 elem 而不是 p

应该是这样

 copy(other.elem,other.elem + other.size,p);

除非你从书中复制错误,否则这确实应该向 Stroustrup 指出,因为我在任何版本或印刷的勘误表中都找不到任何相关内容。

【讨论】:

  • 感谢您的回答。我确实抄对了,因为我发现他的书第二版中有很多错别字
【解决方案2】:

给定:

  • Vector::elem 是 double* 类型的值
  • Vector::size 是某个整数类型的值(比如 int)

那么你的理解是正确的。

请记住,成员变量elem 有两个功能——一个是指向双精度序列,第二个是实际“拥有”已分配的内存。

所以顺序是:

// allocate a sequence large enough, make p point to it
double* p = new double[other.size]; 

// delete our existing elem. i.e. destruct all items in 
// the sequence and free the memory containing the sequence.
delete[] elem;

// at this point p is valid and elem is pointing to memory we no longer own

// make elem point to the newly allocated sequence, p
elem = p;

// at this point, both p and elem point to the new sequence of doubles.
// p will drop out of scope, but since it's a raw pointer, this has
// no effect on the memory it was pointing at.

【讨论】:

  • 感谢您的回答!但我还有一个问题:我应该复制到新数组吗? '复制(other.elem,other.elem + other.size,p)'
猜你喜欢
  • 2020-04-09
  • 2010-12-11
  • 1970-01-01
  • 2011-01-07
  • 2014-09-06
  • 2013-06-15
  • 1970-01-01
相关资源
最近更新 更多