Re: Allocating a local variable to a member function
I have a member variable: std::map<int, CAgents> m_AgentsList;
CAgents is just a really small class with some member variables. Just
really a container for agent data.
Agents log in to a server. In my login function I do this:
myagent.m_Socket = pSocket;
myagent.m_strLogin = strLogin;
m_AgentsList[dwDevice] = myagent;
pSocket is a pointer to the client socket.
Basically I need to make a copy of the client socket. But I am
allocating a local variable to a member variable. When the function
returns myagent is no more. Will this not matter because the data is
copied to m_AgentsList? What about pSocket?
I assume pSocket is of a real pointer type, something like CSocket*? In
that case, you can copy pointer values around as much as you like, you
just need to be careful that the pointee only gets deleted once, and
only when you really don't want it any more.
The standard containers are value based, and therefore when you add an
element to a container, it is copied into the container, and the
original value can be discarded. However, this means that classes used
in containers need to be freely copyable and assignable. Your class is
copyable in the trivial sense that the value is copied, but the copying
doesn't do any resource management, and it does not keep track of
resource ownership. The easiest solution is to modify your CAgents class
to use self-managing members. e.g.
public: //note the public member variables are frowned upon!
Here I've changed m_Socket so that it shares ownership of the socket
with its copies. You should change the type of pSocket to be a
shared_ptr too. See www.boost.org if you haven't got shared_ptr already.