简体   繁体   中英

Initialize a vector inside a struct

I have the following struct:

struct MsgProperties
{
    DWORD               msgSize;
    std::vector<BYTE>   vbuffer;

    //-Constructor
    MsgProperties(DWORD A = 0) : msgSize(A){}
};

I want to use that struct with a c++ vector so this is what I've done:

std::vector<MsgProperties> ReadText;
BYTE buffer[MAX_BUFFER_SIZE];
DWORD bytesRead;
do
{
    bytesRead = myFile.Read(buffer, MAX_BUFFER_SIZE);
    ReadText.push_back(MsgProperties(bytesRead, std::vector<BYTE>((BYTE*)buffer, (BYTE*)buffer + bytesRead)));

} while (bytesRead > 0);

but I can't figure out how to make it work correctly. Can someone tell me what I am missing?

Looks like you need another 2 constructors:

MsgProperties(DWORD A, const std::vector<BYTE>& vec) : msgSize(A), vbuffer(vec) {}
MsgProperties(DWORD A, std::vector<BYTE>&& vec) : msgSize(A), vbuffer(vec) {}

Alernatively, a single constructor would be good too:

MsgProperties(DWORD A, std::vector<BYTE> vec) : msgSize(A), vbuffer(std::move(vec)) {}

On a side note, I do not see why you need message size at all. the size of the vector is the message size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM