复制分配说明(C ++)

时间:2018-01-06 16:25:09

标签: c++

以下是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

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

我的理解是否正确?

我不明白(或者至少目前我的大脑不能接受它),如果我们释放旧空间,为什么可以为它分配新元素?

2 个答案:

答案 0 :(得分:2)

问题在于

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的东西,因为我在任何版本或印刷的勘误表中都找不到任何关于它的内容。

答案 1 :(得分:0)

下式给出:

  • 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.