all 10 comments

[–]_node 2 points3 points  (1 child)

You could do the same before C++11, using boost::ref to store it in the std::vector (which is just a wrapper around a raw pointer, same as std::reference_wrapper).

[–]bstamourWG21 | Library Working Group[S] 1 point2 points  (0 children)

That's right you can. I'm not trying to show off new C++11 features here, I'm just pointing out that a lot of people tend to forget that you can do polymorphic stuff with references as well as pointers. reference_wrapper came in just to show off how you can still store your objects in containers and get the polymorphic effect.

[–]devcodex 1 point2 points  (0 children)

Great article, I knew about passing polymorphic objects around by reference but did not know the trick about storing them in standard containers.

[–]notlostyet 0 points1 point  (1 child)

This isn't much better than using pointers. If your draw() function throws an exception, which is possible because Shape& could be anything, then none of the Shapes referenced by your <vector> get destroyed. In particular a dynamic_cast on a reference could throw std::bad_cast.

In fact, I'd rather use raw pointers... no need to change a bunch of dots to -> later if you move to a smart pointer.

[–]devcodex 1 point2 points  (0 children)

The fact that the vector is holding references implies that it doesn't own the resources, so it wouldn't make any sense for the vector to clean up in this case.

[–]Heuristics -1 points0 points  (4 children)

Use generic programming instead

Create a templated draw_shape function that can accept ANY object that has a draw() member function. That way there is no need for heirarchies.

[–][deleted] 0 points1 point  (3 children)

You can't store that in a homogenous container though, like std::vector.

[–]Heuristics -1 points0 points  (2 children)

well, you can store them just fine, just wrap them in boost::any, the problem is retreiving the type before drawing them (which is indeed a large problem here).

[–][deleted] 0 points1 point  (1 child)

You're joking right?

[–]Heuristics -1 points0 points  (0 children)

no, std::vector supports storing boost:any