【问题标题】:I am stuck with copying a class given an address, I am segfaulting我坚持复制一个给定地址的类,我在段错误
【发布时间】:2014-09-15 05:59:33
【问题描述】:

我已经为此苦苦挣扎了一段时间,但我真的无法理解,我只是遇到了段错误。我正在尝试复制一个类,我要复制的函数也在下面。划掉的是我试过的组合都没有成功,是时候求助了

class Scene
{  private:
int max;
   int* x_row, *y_col;          // maximum and min coordinates of each image
   Image**image_layers;
}


void Scene::_copy(const Scene &source)                                        
{
max = source.max;                    
x_row = new int[source.x_row];
y_col = new int[source.y_col];
image_layers = new Image*[source.max]; 

for(int i = 0; i < source.max; i++)
{
    if(source.image_layers[i] != NULL)
    {
        //image_layers[i] = new Image(*(source.image_layers[i]));  
        // image_layers[i] = new Image;
        //*image_layers[i] = *source.image_layers[i];


        // image_layers[i] = source.image_layers[i]; 

    }
    else
    {   
        image_layers[i] = NULL;
    }
    x_row[i] = source.x_row[i];
    y_col[i] = source.y_col[i];


}

编辑:

我忘了说这个函数叫做“scene(*set)”

【问题讨论】:

  • 是 C++ 吗?添加语言标签。
  • 是的,是c++语言
  • 你难道不好奇 target 对象 (*this) 中的 x_rowy_colimage_layers 引用的数据会发生什么变化吗?调用这个东西,或者你对随后的内存泄漏感到满意。而这个:image_layers[i] = source.image_layers[i] 除了指针之外不复制任何东西(并且在该过程之前立即泄漏分配)。完成后,您将有两个对象持有指向同一图像的指针。
  • 我的教授不喜欢内存泄漏

标签: c++ function class pointers


【解决方案1】:

段错误发生在这里或因此:

x_row = new int[source.x_row];
y_col = new int[source.y_col];

在右侧,您使用地址source.x_row 作为数组大小。这是一个非常大的数字,很可能会导致分配失败。 您需要保留一个成员来保存大小或更好地使用std::vector&lt;int&gt; 对象。

使用 memcpy 可以更快地复制 C 数组。使用 C++ 向量,您可以将一个分配给另一个:

x_row = source.x_row

与问题无关,但此函数应命名为operator=,通过将一个实例分配给另一个实例,可以更轻松地使用该类:

Scene & Scene::operator=(const Scene &source)                                        
{
    // copy elements
    ...

    return *this;
}

【讨论】:

    【解决方案2】:
    x_row = new int[source.x_row];
    y_col = new int[source.y_col];
    

    你确定上面的代码吗? source.x_row 是指针

    【讨论】:

    • 因为它是一个场景对象
    猜你喜欢
    • 1970-01-01
    • 2017-01-18
    • 2012-07-20
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多