dpeterson3
dpeterson3

Reputation: 13

How to add a 'new' class to a vector

I am writing a server in C++ and created a class called client to store information about connected clients. I wanted to store the clients in a vector. I have a call

clients.push_back(new client(addr,fd));

to add a client object to the vector clients. I get the following error on compile

server.cpp:67: error: no matching function for call to ‘std::vector<client, std::allocator<client> >::push_back(client*)

I think it has something to do with my misunderstanding of the new keyword and how data is stored/moved in C++. I come from a Java background, so I am not use to pointers and memmory stuff of C++.

Upvotes: 1

Views: 6100

Answers (3)

Christopher Hunt
Christopher Hunt

Reputation: 2081

Assuming you can use the boost library, you might also want to consider something like (untested):

typedef ClientSharedPtr boost::shared_ptr<Client>;
std::vector<ClientSharedPtr > clients;
ClientSharedPtr client(new Client());
clients.push_back(client);

This way, you'll get pointers to client automatically managed.

Alternatively, consider providing a copy constructor on Client and then:

std::vector<Client> clients;
Client client;
clients.push_back(client);

A copy of client will then occur when it is pushed on to the vector.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490048

You almost certainly just want to get rid of the new so it's:

clients.push_back(client(addr, fd));

In Java you have to explicitly new all your objects, but in C++ you not only don't need to, but generally want to avoid it when/if at all reasonable.

Upvotes: 4

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

How did you create your vector?

You need to pass a template parameter of Client* so you'd have std::vector<Client*> clients; if you want to store pointers inside. If you use this method and use raw pointers which point to memory on the heap (such as when created with new), remember that you will need to eventually iterate through each element of your vector and call delete on each element.

Or if you don't mind your Client objects being copied you can use std::vector<Client> clients; and then call clients.push_back(myClient);

Upvotes: 4

Related Questions