M
mike3
Hi.
Is this bad? Suppose you have something like this:
---
class Shape {
... blah ...
};
class Rectangle : public Shape {
... blah ...
};
class Circle : public Shape {
... blah ...
};
.... blah ...
class Drawing {
private:
... blah ...
std::vector<Shape *> shapeList;
... blah ...
public:
... blah ...
void addShape(Shape *s)
{
shapeList.push_back(s);
}
... blah ...
void doSmth(); // uses the objects in shapeList somehow
... blah ...
};
---
There could arise a situation like this:
---
void someFunction()
{
Drawing drawing;
... blah ...
{
Circle circle(35.0, 55.0, 25.0); // make a circle & (35, 55)
with
// radius 25
drawing.addShape(&circle); // add it to the drawing
// OOPS! circle goes out of scope...!
}
... blah ...
drawing.doSmth(); // BOOM!
... blah ...
}
---
What to do? Now one could, I suppose, change to Circle* circle = new
Circle(35.0, 55.0, 25.0);, but then we need something to take care of
the garbage. Adding a delete() in, say, the destructor for Drawing
might work, but we make some assumptions that may or may not be true,
i.e. one can break it by misusing it, e.g. if one does not use a new
to get the parameter or one forgets that destroying drawing also
destroys circle, etc. Is it a bad idea to rely on the user's
understanding -- to me it doesn't seem so. What should be done?
Is this bad? Suppose you have something like this:
---
class Shape {
... blah ...
};
class Rectangle : public Shape {
... blah ...
};
class Circle : public Shape {
... blah ...
};
.... blah ...
class Drawing {
private:
... blah ...
std::vector<Shape *> shapeList;
... blah ...
public:
... blah ...
void addShape(Shape *s)
{
shapeList.push_back(s);
}
... blah ...
void doSmth(); // uses the objects in shapeList somehow
... blah ...
};
---
There could arise a situation like this:
---
void someFunction()
{
Drawing drawing;
... blah ...
{
Circle circle(35.0, 55.0, 25.0); // make a circle & (35, 55)
with
// radius 25
drawing.addShape(&circle); // add it to the drawing
// OOPS! circle goes out of scope...!
}
... blah ...
drawing.doSmth(); // BOOM!
... blah ...
}
---
What to do? Now one could, I suppose, change to Circle* circle = new
Circle(35.0, 55.0, 25.0);, but then we need something to take care of
the garbage. Adding a delete() in, say, the destructor for Drawing
might work, but we make some assumptions that may or may not be true,
i.e. one can break it by misusing it, e.g. if one does not use a new
to get the parameter or one forgets that destroying drawing also
destroys circle, etc. Is it a bad idea to rely on the user's
understanding -- to me it doesn't seem so. What should be done?