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::vecto开发者_高级运维r<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++.
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.
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);
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.
精彩评论