创建一个列C的深层副本++ [英] Create a deep copy of an array C++

查看:188
本文介绍了创建一个列C的深层副本++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决我的程序有些问题,这似乎是有或者是与我的拷贝构造函数或析构函数的问题。我得到一个内存异常。

任何帮助将我AP preciated
谢谢

  ArrayStorage :: ArrayStorage(常量ArrayStorage&安培; A):readArray(a.readArray),ARRAYSIZE(a.arraysize)
{
    readArray =新的字符串[ARRAYSIZE] //创建数组    的memcpy(readArray,a.readArray,的sizeof(字符串)* ARRAYSIZE); //复制字节的值从该位置指向由烃源和目的地。
}ArrayStorage ::〜ArrayStorage(无效)
{
    删除[](readArray); // deconstuctor删除阵列。
}

这会是一个更好的方式比其他的memcpy数组复制:

 的for(int i = 0; I< ARRAYSIZE;我++)
    {
        readArray [I] = a.readArray [I]
    }


解决方案

您不能只是的memcpy 随机对象,你需要真正用自己的复制操作复制它们。

字符串最有可能拥有一个指向堆分配存储。如果你把它复制位运算,要求原始字符串析构函数的无效复制字符串的数据。

使用类似的std ::复制正确做到这一点。

 的#include<&算法GT;
...
性病::复制(a.readArray,a.readArray + ARRAYSIZE,readArray);

I am try to solve some problems in my program and it would appear that there is either a problem with my copy constructor or with my destructor. I am getting a memory exception.

any help would me appreciated Thanks

ArrayStorage::ArrayStorage(const ArrayStorage &a):readArray(a.readArray),arraysize(a.arraysize)
{
    readArray = new string[arraysize]; //create the array

    memcpy (readArray,a.readArray,sizeof(string)*arraysize);//Copy the values of bytes from the location pointed at by the souce and destination.
}

ArrayStorage::~ArrayStorage(void)
{
    delete[](readArray);//deconstuctor to delete the array.
}

would this be a better way to copy the array other than memcpy :

for (int i = 0 ; i < arraysize ; i ++)
    {
        readArray[i] = a.readArray[i];
    }

解决方案

You can't just memcpy random objects, you need to actually copy them with their copy operators.

string most likely holds a pointer to heap-allocated storage. If you copy it bitwise, calling the destructor on the original string invalidates the "copied" string's data.

Use something like std::copy to do this properly.

#include <algorithm>
...
std::copy(a.readArray, a.readArray+arraysize, readArray);

这篇关于创建一个列C的深层副本++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆