On Sunday, 24 August 2014 at 11:56:44 UTC, nikki wrote:
I come from languages that don't offer structs, I have this json load function that has to keep some data and intuitively I've written a struct, I've read about the differences, heap vs stack, value vs reference, but know I think i am overthinking it.

Is this decent:
        bool loadFromFile (string path)
        {
                auto data = readText(path);
                JSONValue parsed = parseJSON(data);
                
                struct AtlasSpriteData
                {
                        SDL_Rect clipRectangle;
                        int xOffset;
                        int yOffset;
                }
                AtlasSpriteData[string] dict;

                foreach( string name, value; parsed["frames"] ){
                        SDL_Rect clipRectangle;
auto spriteSourceSize = value["spriteSourceSize"];
                        clipRectangle.x = to!int(frame["x"].toString());
                        clipRectangle.y = to!int(frame["y"].toString());
                        clipRectangle.w = to!int(frame["w"].toString());
                        clipRectangle.h = to!int(frame["h"].toString());
                        int xOffset = to!int(spriteSourceSize["x"].toString());
                        int yOffset = to!int(spriteSourceSize["y"].toString());
                        auto data = AtlasSpriteData(clipRectangle, xOffset, 
yOffset);
                        dict[name] = data;
                }

Or should I use a class for that AtlasSpriteData?
reading about it I get the impression everytime I'll look up data from that dictionary data will get copied ?

Your struct instance will occupy only 24 bytes. It's ok even if you will copy it. I would avoid heap allocation in this case. Also what is 'frame' variable? I don't see local declaration of it. Or you just forgot to replace 'value' with 'frame'. Does not JSONValue.integer fit in this case instead of to!int(JSONValue.toString()) ?

Reading does not perform copy if you access struct directly as dict[name].some_field. Copying is performed only if you pass struct by value or assign it to variable.

Reply via email to