0

So I'm working with an API which really isn't as functional as it could be. (Quickhaptics to be specific) In order to make something that I have work, I need to delete an object within a structure, create it again, (without using new, because the constructor for the object doesn't work the way I need it to) then set it to something.

I'm trying to do something along the lines of

delete data.cursor;
Cursor* data.cursor = (Cursor*)malloc(sizeof(Cursor));
data.cursor = data.cursors[index];

But this causes a crash(EDIT sorry, it doesn't compile is what I meant to say, but I don't understand the compiler errors)

Additional info: The way the API works, I need to send it a pointer to an item, which it takes initially and writes information to throughout execution. I'm trying to update the mesh on a cursor type object. It provides update functions to load in new meshes, but they are very expensive and can only run at ~3 fps. My solution is to load the objects into an array at startup, then just switch out the object that the program looks for as a cursor.

I'm generally new to C++, and my experience is all from sitting down and typing with no instruction, so there may be some basic C++ thing that I'm missing.

EDIT: Just to be clear, doing this works, just very slowly

delete data.cursor;
data.cursor = new Cursor("filename");

where data.cursors[index] was declared in teh same exact way at startup

4

2 回答 2

3

看起来好像您已经在地址分配了内存,malloc()然后将地址值设置为某个对象,也许?您最可能想要的是如下一行

*data.cursor = data.cursors[index];

*将取消引用该位置的内存,以便您可以设置其值。但是请注意,这将调用operator=.

只是一个旁注:

混合new/deletemalloc()/free()通常是一个坏主意,因为您需要跟踪对象的分配方式。也就是说,您必须将正确的释放调用与它们各自的分配调用一起使用。

于 2012-04-26T15:59:33.403 回答
0

它无法编译,因为您试图声明一个成员:

delete data.cursor;
Cursor* data.cursor = (Cursor*)malloc(sizeof(Cursor));

是非法的,应该是:

delete data.cursor;
data.cursor = (Cursor*)malloc(sizeof(Cursor));

此外,因为cursor是一个指针,做

data.cursor = data.cursors[index];

将使指针指向该内存,因此先前分配的内存(通过malloc(sizeof(Cursor));将被泄漏。您可能正在寻找memcpy这里。

于 2012-04-26T16:06:50.363 回答