Re: pointer in queue
James Kanze wrote:
On Feb 2, 10:07 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
Ian Collins wrote:
Carl Forsman wrote:
I have a deque object.
Can I insert pointers into the queue? (I heard I cannot
insert pointer into a queue)
like this:
===============
std::deque < Sock* > * socks;
socks = new deque< Sock* >;
Why use new here?
int port = 4322;
for ( int i = 0; i< 10; i++ ) {
Sock * sock = new Sock();
sock->Create1(this, port);
socks->push_back(sock);
}
later I will loop the queue of socket:
===============
for ( std::deque<Sock>::const_iterator iter = socks->begin(); iter !=
socks->end(); iter++ ) {
for ( std::deque<Sock*>::const_iterator iter = socks->begin();
iter != socks->end(); ++iter ) {
Sock temp = iter->first; // get the 1st socket
A deque iterator does not have a member first.
Unless you want to copy the object, you would require:
const Sock& temp = **iter;
Note the use of const reference. *iter is a Sock*.
[snip]
The queue contains Sock* not Sock const *. The use of a
const_iterator only implies that the Sock* inside the queue
cannot be cahnged, but that doesn't make the pointee const
Sock. So,
Sock & temp = **temp;
is possible too would work when inside the loop non-const
methods of Sock are called.
The correct handling of const might be an argument for not using
pointers. IMHO, the real question here isn't whether you can
have a deque< Sock* > (obviously you can), but whether you want
to. If Sock has identity, or if the container contains
polymorphic objects, you need to use the pointer version, but
otherwise, I'd stick with putting the objects themselves in the
container.
I agree. However, in my mind, one natural implementation of sockets would
treat them as objects with identity. So, I took no issue with the decision
to use pointers in the container.
Personally, I have a very strong inclination towards value classes. Thus, I
probably would implement a socket_handle rather than a socket. Handles then
would be values: pretty much like (appropriate smart) pointers, except that
the constructors could make sure that 0 is not a valid value. But that is
probably just my personal preference.
Best
Kai-Uwe Bux