Variable Sized Struct C++

前端 未结 10 1105
忘掉有多难
忘掉有多难 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:44

    You probably want something lighter than a vector for high performances. You also want to be very specific about the size of your packet to be cross-platform. But you don't want to bother about memory leaks either.

    Fortunately the boost library did most of the hard part:

    struct packet
    {
       boost::uint32_t _size;
       boost::scoped_array _data;
    
       packet() : _size(0) {}
    
           explicit packet(packet boost::uint32_t s) : _size(s), _data(new unsigned char [s]) {}
    
       explicit packet(const void * const d, boost::uint32_t s) : _size(s), _data(new unsigned char [s])
       {
            std::memcpy(_data, static_cast(d), _size);
       }
    };
    
    typedef boost::shared_ptr packet_ptr;
    
    packet_ptr build_packet(const void const * data, boost::uint32_t s)
    {
    
        return packet_ptr(new packet(data, s));
    }
    

提交回复
热议问题