Variable Sized Struct C++

前端 未结 10 1123
忘掉有多难
忘掉有多难 2020-11-30 04:48

Is this the best way to make a variable sized struct in C++? I don\'t want to use vector because the length doesn\'t change after initialization.

struct Pack         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 05:40

    This is OK (and was standard practice for C).

    But this is not a good idea for C++.
    This is because the compiler generates a whole set of other methods automatically for you around the class. These methods do not understand that you have cheated.

    For Example:

    void copyRHSToLeft(Packet& lhs,Packet& rhs)
    {
        lhs = rhs;  // The compiler generated code for assignement kicks in here.
                    // Are your objects going to cope correctly??
    }
    
    
    Packet*   a = CreatePacket(3);
    Packet*   b = CreatePacket(5);
    copyRHSToLeft(*a,*b);
    

    Use the std::vector<> it is much safer and works correctly.
    I would also bet it is just as efficient as your implementation after the optimizer kicks in.

    Alternatively boost contains a fixed size array:
    http://www.boost.org/doc/libs/1_38_0/doc/html/array.html

提交回复
热议问题