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..
A vector<char>
is essentially just a managed character array.
So you can write:
{
vector<char> buf(4096);
...
int result = recv(fd, &buf[received_so_far], buf.size() - received_so_far);
...
}
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 buf
will allocate the underlying array on the heap, and it will free it automatically when buf
goes 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 another vector<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.
using vector is:
My main reason:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With