错误,动态地将对象分配给数组

Dar*_*ium 0 c++ dynamic dynamic-memory-allocation

我有一个指向结构数组的指针,如下所示:

class Terrian  {
     ...
    private:
        Vector *terrian_vertices;
     ...
}
Run Code Online (Sandbox Code Playgroud)

并且指针的数据在"construct_vertices"函数中生成

Terrian::Terrian(int width, int height)  {
    this->width = width;
    this->height = height;

    std::cout << "Width: " << width << "  Height: " << height << "\n";

    std::cout << "Vertices\n";
    construct_vertices();
    std::cout << "Element\n";
    construct_elements();
    std::cout << "Buffers\n";
    construct_buffers();
}

void Terrian::construct_vertices()  {
    terrian_vertices = new Vector[width * height];

    std::cout << "Generating data\n";

    for (int x = 0; x < width; x++)  {
        for (int y = 0; y < height; y++)  {
            int index = x + y * width;

            Vector *pos = new Vector((GLfloat)x, 0.0f, (GLfloat)-y);
            memcpy(pos, terrian_vertices, sizeof(Vector) * index);

            std::cout << terrian_vertices[index].x;

            Color *color = new Color(0, 255, 0);
            memcpy(color, terrian_colors, sizeof(Color) * index);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是程序的输出(我在main函数中做的只是实例化对象)

Width: 32  Height: 32
Vertices
Generating data
5.2349e-039
Process returned -1073741819 (0xC0000005)   execution time : 10.073 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)

当第一个指针被复制到数组时程序崩溃,'x'的输出应为0.这令人费解.有谁知道造成这种情况的原因是什么?如果是这样,有没有更好的方法动态分配结构 - 不使用memcpy?

R. *_*des 5

有谁知道造成这种情况的原因是什么?

使用memcpy不正确.任何参考文档都会告诉你.

第一个参数是指向目标的指针,它将是数组中的index元素terrian_vertices:terrian_vertices + index.

第二个参数是指向源的指针,即pos.

(如果你很好奇,目的而来的源之前的原因是因为它平行的赋值运算符:destination = source)

第三个参数是数据的复制,而你的情况也只是量sizeof(Vector):这只是一个 Vector需要复制,没有index.

memcpy像代码一样滥用很容易导致未定义的行为,这很幸运地表现为错误.

如果是这样,有没有更好的方法动态分配结构 - 不使用memcpy?

是.不要自己管理内存:使用std::vector和正常复制语义.

class Terrian  {
// ...
private:
    std::vector<Vector> terrain_vertices;
    // Hmm, this may need some touch up on naming,
    // or it may get confusing with two "vector" thingies around
};

// ...

void Terrian::construct_vertices()  {
    terrain_vertices.reserve(width * height);
     // reserve is actually optional,
     // but I put it here to parallel the original code
     // and because it may avoid unneeded allocations

    std::cout << "Generating data\n";

    for (int x = 0; x < width; x++)  {
        for (int y = 0; y < height; y++)  {
            terrain_vertices.emplace_back((GLfloat)x, 0.0f, (GLfloat)-y);
            // or this if your compiler doesn't support C++11:
            // terrain_vertices.push_back(Vector((GLfloat)x, 0.0f, (GLfloat)-y));

            std::cout << terrian_vertices[index].x;

            // same thing for colors
            terrain_colors.emplace_back(0, 255, 0);
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意现在new看不到任何地方.这解决了原始代码的另一个问题:它正在泄漏每个循环迭代的一个实例Vector和一个实例Color.