开发者

Can't initialize vector C++

SockeClient.h file

#define SIZE_OF_BUFFER 4096

class SocketClient {

public:
    SocketClient(int cfd);
    virtual ~SocketClient();

    int recv();
    int getFd();

protected:
    int             m_fd;
    char            *m_buffer;
    vector<char>    m_vbuffer;

};

I was trying to do

vector<char>    m_vbuffer(SIZE_OF_BUFFER);开发者_开发问答

And I got a syntax error... How do I initialize the vector with size of 4096. Thanks in advance


Use member-initialization-list, in the constructor's definition as:

class SocketClient {

public:
    SocketClient(int cfd) : m_vbuffer(SIZE_OF_BUFFER) 
    {                   //^^^^^^^^^^^^^^^^^^^^^^^^^^^ member-initialization-list

         //other code... 
    }


protected:
    int             m_fd;
    char            *m_buffer;
    vector<char>    m_vbuffer;

};

You can use member-initialization-list to initialize many members as:

class A
{
  std::string s;
  int a;
  int *p;
  A(int x) : s("somestring"), a(x), p(new int[100])
  {
    //other code if any
  }
 ~A()
  {
     delete []p; //must deallocate the memory!
  }
};


Call m_vbuffer->reserve(SIZE_OF_BUFFER) in the constructor of SocketClient.


In addition to other answers consider using some circular buffer instead of vector. There is one in boost.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜