I am working on a network programming and I have seen people using vector as the input buffer for socket instead of char array.
I was wondering what it the advantage of doing this.
Thanks in advance..
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
vector<char>is essentially just a managed character array.So you can write:
The vector “knows” its size, so you can use
buf.size()everywhere and never have to worry about overrunning your buffer. You can also change the size in the declaration and have it take effect everywhere without any messy #defines.This use of
bufwill allocate the underlying array on the heap, and it will free it automatically whenbufgoes out of scope, no matter how that happens (e.g. exceptions or early return). So you get the nice semantics of stack allocation while still keeping large objects on the heap.You can use
buf.swap()to “hand ownership” of the underlying character array to anothervector<char>very efficiently. (This is a good idea for network traffic… Modern networks are fast. The last thing you want to do is to create yet another copy of every byte you receive from the network.) And you still do not have to worry about explicitly freeing the memory.Those are the big advantages that come to mind off the top of my head for this particular application.