Is this C++ structure initialization trick safe?

前端 未结 16 1158
有刺的猬
有刺的猬 2020-12-23 17:56

Instead of having to remember to initialize a simple \'C\' structure, I might derive from it and zero it in the constructor like this:

struct MY_STRUCT
{
            


        
16条回答
  •  感情败类
    2020-12-23 18:43

    It's a bit of code, but it's reusable; include it once and it should work for any POD. You can pass an instance of this class to any function expecting a MY_STRUCT, or use the GetPointer function to pass it into a function that will modify the structure.

    template 
    class CStructWrapper
    {
    private:
        STR MyStruct;
    
    public:
        CStructWrapper() { STR temp = {}; MyStruct = temp;}
        CStructWrapper(const STR &myStruct) : MyStruct(myStruct) {}
    
        operator STR &() { return MyStruct; }
        operator const STR &() const { return MyStruct; }
    
        STR *GetPointer() { return &MyStruct; }
    };
    
    CStructWrapper myStruct;
    CStructWrapper anotherStruct;
    

    This way, you don't have to worry about whether NULLs are all 0, or floating point representations. As long as STR is a simple aggregate type, things will work. When STR is not a simple aggregate type, you'll get a compile-time error, so you won't have to worry about accidentally misusing this. Also, if the type contains something more complex, as long as it has a default constructor, you're ok:

    struct MY_STRUCT2
    {
        int n1;
        std::string s1;
    };
    
    CStructWrapper myStruct2; // n1 is set to 0, s1 is set to "";
    

    On the downside, it's slower since you're making an extra temporary copy, and the compiler will assign each member to 0 individually, instead of one memset.

提交回复
热议问题