Re: Templated containers of inherited objects
On 17 Feb 2007 12:30:46 -0800, "paul.joseph.davis" wrote:
On Feb 17, 1:12 pm, rpbg...@yahoo.com (Roland Pibinger) wrote:
Just look at the containers, iterators and algorithms. No algorithm
works with (pointers to) objects (except random_shuffle).
This examples shows how to use std::sort on a std::vector or pointers.
As well as a trivial example of std::for_each to print the vector.
#include <iostream>
#include <vector>
class A
{
public:
A( int val )
{
_val = val ;
}
~A() {}
int
value()
{
return _val ;
}
private:
int _val ;
} ;
bool
compare( A* lhs, A* rhs )
{
return lhs->value() < rhs->value() ;
}
This is the workaround. As said before no algorithm (except
random_shuffle) works with pointers out of the box.
void
echo( A* a )
{
std::cout << a->value() << std::endl ;
}
int
main( int argc, char* argv[] )
{
std::vector< A* > vec ;
for( int i = 10 ; i > 0 ; i-- )
{
A* a = new A( i ) ;
vec.push_back( a ) ;
}
// compiles but wrong result
std::sort( vec.begin(), vec.end()) ;
// ditto; 2 dereferences needed to access the object
for (std::vector<A*>::iterator i = vec.begin(); i != vec.end(); ++i) {
std::cout << *i << std::endl;
}
const std::vector<A*>& const_vec = vec;
// changing pointed-to element in const vector
*const_vec[0] = 3;
// changing pointed-to element through const_iterator
// 2 dereferences needed to access the object.
**const_vec.begin() = 4;
std::cout << "Before sort:" << std::endl ;
std::for_each( vec.begin(), vec.end(), echo ) ;
std::sort( vec.begin(), vec.end(), compare ) ;
std::cout << "After sort:" << std::endl ;
std::for_each( vec.begin(), vec.end(), echo ) ;
// leaking objects
}
Objects (in the meaning used in object-oriented programing) are
characterized by identity, state and behavior. It makes no sense to
copy or assign objects. Copy constructibility makes only sense for
values and value-oriented libraries like STL.
You're right, wrong, and neither right or wrong. Of course objects are
characterized by their state and behavior. You're absolutely wrong
that it makes no sense to copy or assign objects, there are instances
where this may be true, but its just plain wrong to say never. I use
it quite a bit.
When identity is important (which is the case with objects) then
duplicate instances are always problematic (not to speak of
assignment).
Best wishes,
Roland Pibinger