'Best way to reset all struct elements to 0 C++ [duplicate]

I'm trying to create some variables within certain structs, and I need to create a function that would reset all the values in the namespace to 0. I'm aware I can just tediously reset them all to 0 one by one, but I'm certain that's not the best way to do it. Another question I want to ask is that is it alright to initialise all the variables as undefined/NULL? Would that cause any bottlenecks in my code at compile time?

namespace REGISTER {
    struct GPR {
        // 64-bit
        struct R64 {
            uint64_t RAX; // accumulator
            uint64_t RBX; // base
            uint64_t RCX; // counter
            uint64_t RDX; // data
            uint64_t RSP; // stack pointer
            uint64_t RBP; // stack base pointer
            uint64_t RSI; // source index
            uint64_t RDI; // destination index
        } R64;

        // 32-bit
        struct R32 {
            uint32_t EAX;
            uint32_t EBX;
            uint32_t ECX;
            uint32_t EDX;
            uint32_t ESP;
            uint32_t EBP;
            uint32_t ESI;
            uint32_t EDI;
        } R32;

        // 16-bit
        struct R16 {
            uint16_t AX;
            uint16_t BX;
            uint16_t CX;
            uint16_t DX;
            uint16_t SP;
            uint16_t BP;
            uint16_t SI;
            uint16_t DI;
        } R16;

        // 8-bit
        struct R8 {
            uint8_t AH;
            uint8_t BH;
            uint8_t CH;
            uint8_t DH;
            uint8_t AL;
            uint8_t BL;
            uint8_t CL;
            uint8_t DL;

            uint8_t SPL;
            uint8_t BPL;
            uint8_t SIL;
            uint8_t DIL;
        } R8;
    } GPR;

    // Segment registers
    struct SREG {
        uint16_t SS; // stack
        uint16_t CS; // code
        uint16_t DS; // data
        uint16_t ES; // extra data
        uint16_t FS; // more extra data
        uint16_t GS; // still more extra data
    } SREG;

    // Pointer registers
    struct PREG {
        uint64_t RIP;
        uint32_t EIP;
        uint16_t IP;
    } PREG;
};
c++


Solution 1:[1]

I see you're getting some suggestions to use memset. I think that's a mistake. It might be perfectly fine with the data you have, but as soon as someone down the road adds a string to your class, suddenly that's bad.

I would give each of them a default value of zero and then use the assignment operator to a newly-constructed version.

It's good practice to automatically initialize all your values, anyway -- to 0 or nullptr or whatever makes sense. Leaving them undefined the way you have is a big opportunity for bugs.

So: GPR blank; *this = blank;

And you would be good to go.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Larson