Search code examples
arraysglobal-variablesdref

Is it possible to add a new local struct to a global associative array without creating a copy?


I am trying to add a new struct to a global associative array from within a function. When I create a new struct directly in the array and then manipulate it by a pointer everything is fine:

myObject[string] globalArray;

myObject * addMyObject(string d) {
    myObject * p;
    globalArray[d] = *(new myObject);
    p = &(globalArray[d]);
    [do changes to myObject by p]
    return p;
}

But if I create a local object first and then assign its pointer to an element of the global array it misbehaves. I can see that a copy of the object is created for the array. Any changes to a local object are lost and the next time I access this element from the global array it's basically blank (unchanged new struct).

myObject * addMyObject(string d) {
    myObject * p;
    p = new myObject;
    globalArray[d] = *p;
    [do changes to myObject by p]
    return p;
}

I still would like to go with a second way of creating a local object first. But what should I change in the code, so that a created object is not local anymore but is truly an element of the global array?

Thanks!


Solution

  • Structs are copied by value, there is no way around that. You can either switch to classes or pointers in the array, which would solve your problem.

    If you really want to keep struct data directly in the associative array, you will need to insert the object into the array first, and then take its pointer after which you can modify it.

    myObject* addMyObject(string d) {
        globalArray[d] = myObject();
        auto p = &globalArray[d];
        [do changes to myObject by p]
        return p;
    }