Re: STL & pipe, socket descriptors
M.Endraszka@gmail.com wrote:
On 16 Cze, 22:38, "Thomas J. Gritzan" <Phygon_ANTIS...@gmx.de> wrote:
You definitly violate the "rule of three". That may be the problem here.
Google for it. If it works with a reserve(3) in this example, that this
is your problem. The vector copies your objects and makes temporaries
which get destructed, closing your pipes. So the next pipe gets an old
yet unused descriptor.
Ok. I see the sequence is CONSTRUCT TEMP -> COPY TO DESTINATION ->
DESTROY TEMP
which I don't like, but still makes sense.
It's what C++ does.
Writing a copy constructor seems to help
object(object const& in)
{
id = in.id;
pipe(p);
}
IMHO, this is the wrong solution. It creates a lot of pipes, and it makes
the object harder to use (copies aren't equal as one would usually expect).
I also added assigment operator as one of you suggested:
object& operator=(const object& in)
{
p[0] = in.p[0];
p[1] = in.p[1];
}
Though I think compiler generated one would do the same.
Your compiler would generate the same thing. You need the rule of three, but
not this way.
Solution 1)
class object {
... //as before
private:
void operator = (const object&); // No need to actually implement these
object(const object&);
};
vector<boost::shared_ptr<object> > objects;
for (...)
objects.push_back(boost::shared_ptr<object>(new object(i)));
This would make the objects non copyable, and your boost::shared_ptr takes
care of deleting. You could also use std::auto_ptr instead of
boost::shared_ptr.
Solution 2)
class object {
struct arr {
int p[2];
};
boost::shared_ptr<arr> p;
public:
object() : p(new arr)
{ pipe(p->p); }
// compiler generated copy ctor, assignment op and dtor works
//...
};
Boost::shared_ptr can be downloaded from <URL:http://boost.org>. It's also
up for the new standard, and might be found if your compiler ships the tr1
libs. In that case it's called std::tr1::shared_ptr (turn on tr1 and
#include <memory>)
--
rbh