Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using vector<char> as input buffer over char array?

Tags:

c++

networking

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..

like image 511
user800799 Avatar asked Jun 22 '11 05:06

user800799


3 Answers

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.

like image 106
Nemo Avatar answered Oct 18 '22 20:10

Nemo


using vector is:

  • easy to grow-up space of memory.
  • easy to make copy of datas.
  • easy to free.
like image 3
mattn Avatar answered Oct 18 '22 20:10

mattn


My main reason:

  • Its Exception Safe.
    • No matter what goes wrong the vector will not leak memory.
like image 2
Martin York Avatar answered Oct 18 '22 21:10

Martin York