Slicing instances in STL containers

A

AlesD

Hello,

I have problem that when I use std::list<MyClass> and then store
various subclasses of MyClass in that list (or any other STL container)
the instances get sliced.

I have read FAQ: '[20.8] What is a "virtual constructor"?', but I
miss information if there is some "workaround" when using STL
containers, since I can't change them to call clone() instead of copy
constructor.

The solutions I can think about is:
a) Store pointers to MyClass in the container
- for this I have to write custom copy ctr's and operator=() for
all classes using std::list<MyClass>
b) Create wrapper class that "owns" my class
- this wrapper would call clone() to copy the owned instance
- this however one more level of indirection and I will have to
add proxy for almost all methods of MyClass to this wrapper (I make
heavy use of STL algorithms to work with the list

Is there any other "easy" solution to this problem, that I might miss?

Ales
 
K

Kai-Uwe Bux

AlesD said:
Hello,

I have problem that when I use std::list<MyClass> and then store
various subclasses of MyClass in that list (or any other STL container)
the instances get sliced.

I have read FAQ: '[20.8] What is a "virtual constructor"?', but I
miss information if there is some "workaround" when using STL
containers, since I can't change them to call clone() instead of copy
constructor.

The solutions I can think about is:
a) Store pointers to MyClass in the container
- for this I have to write custom copy ctr's and operator=() for
all classes using std::list<MyClass>
b) Create wrapper class that "owns" my class
- this wrapper would call clone() to copy the owned instance
- this however one more level of indirection and I will have to
add proxy for almost all methods of MyClass to this wrapper (I make
heavy use of STL algorithms to work with the list

Is there any other "easy" solution to this problem, that I might miss?

Pointers it is, however, you can make your life easier using smart pointers.
If you want to keep copy semantics, you should use a cloning smart pointer
or a copy smart pointer. Google this group for those terms and you will
find code. If you are happy with reference count base reference semantics,
you can use tr1::shared_ptr. In either case, the compiler provided copy
constructors and assignment operators for classes that contain a

std::my_list< well_chosen_smart_pointer< MyClass > >

will work fine.


Best

Kai-Uwe Bux
 
R

Roland Pibinger

Pointers it is, however, you can make your life easier using smart pointers.
If you want to keep copy semantics, you should use a cloning smart pointer
or a copy smart pointer. Google this group for those terms and you will
find code. If you are happy with reference count base reference semantics,
you can use tr1::shared_ptr. In either case, the compiler provided copy
constructors and assignment operators for classes that contain a

std::my_list< well_chosen_smart_pointer< MyClass > >

will work fine.

Can you explain what will work fine? Sure, tr1::shared_ptr gives you
object lifetime management, albeit the most inefficient known so far
(one dynamically allocted counter for each pointed-to object).
Otherwise, tr1::shared_ptr imitates real pointers and therefore
'inherits' the mismatch between STL value semantics and pointers. So,
why put "smart" pointers into STL containers at all? It makes no
sense.

Best wishes,
Roland Pibinger
 
R

red floyd

Roland said:
will work fine.
[anti-pointer-in-container rant redacted]

OK, Roland. I have the following requirements: I need a container of
polymorphic objects. For various reasons, on this project, I am not
allowed to use third party libraries (don't suggest Rogue Wave).

How do I do it?
 
J

Jens Theisen

Roland said:
Can you explain what will work fine? Sure, tr1::shared_ptr gives you
object lifetime management, albeit the most inefficient known so far
(one dynamically allocted counter for each pointed-to object).

Boost's implementation can be configured to use a memory pool, so it
doesn't dynamically allocate a pointer per pointed-to object.

But admittedly, I don't know any other decent smart pointer
implementation. Can you point me to one or more?

Jens
 
S

Squeamizh

Roland said:
Can you explain what will work fine? Sure, tr1::shared_ptr gives you
object lifetime management, albeit the most inefficient known so far
(one dynamically allocted counter for each pointed-to object).
Otherwise, tr1::shared_ptr imitates real pointers and therefore
'inherits' the mismatch between STL value semantics and pointers. So,
why put "smart" pointers into STL containers at all? It makes no
sense.

Could you please explain what you mean by mismatch, and--if
possible--provide an alternate solution that avoids it?
 
R

Roland Pibinger

Roland said:
will work fine.
[anti-pointer-in-container rant redacted]

Which rant? I've asked a simple question and now I get only counter
questions instead of an answer.
OK, Roland. I have the following requirements: I need a container of
polymorphic objects.

Not an uncommon requirement.
For various reasons, on this project, I am not
allowed to use third party libraries (don't suggest Rogue Wave).

I'm not a Rogue Wave salesperson ;-)
How do I do it?

Someone with your skill set can write a container for pointers (real
pointers, of course, not "smart" pointers).

Best wishes,
Roland Pibinger
 
R

Roland Pibinger

Boost's implementation can be configured to use a memory pool, so it
doesn't dynamically allocate a pointer per pointed-to object.

What is the 'heap' or 'free store' but a memory pool?
But admittedly, I don't know any other decent smart pointer
implementation. Can you point me to one or more?

You don't need any smart pointer. You need
containers/iterators/algorithms that work appropriately with pointers.

Best wishes,
Roland Pibinger
 
R

Roland Pibinger

Could you please explain what you mean by mismatch, and--if
possible--provide an alternate solution that avoids it?

std::vector<MyClass*> myVec;
std::sort (myVec.begin(), myVec.end());

In the above example the sort function template does the wrong thing:
it sorts pointers (addresses). That's the mismatch. It should sort
according to the pointed-to objects but exchange only pointers. The
reason for the strange behavior is that STL was deliberately made
without any awareness for pointers (a.k.a. 'value semantics'). The
'usual' workaround is to provide a user-defined compare object as
third argument - a workaround that confirms the mismatch.

Best wishes,
Roland Pibinger
 
J

Jens Theisen

Roland said:
What is the 'heap' or 'free store' but a memory pool?

shared_ptrs memory pool is a special purpose memory pool which can be
faster since it knows the size of the chunk it's going to allocate in
each step. I don't know how much it gains though.

I agree that it would be beneficial to have an intrusive smart pointer
as an alternative.
You don't need any smart pointer. You need
containers/iterators/algorithms that work appropriately with pointers.

Uh? I'm not sure if I understand exactly what you mean.

The only decent ways of memory management I did come accross so far have
been smart pointers, pools (as in APR), and sophisticated garbage
collection.

Jens
 
J

Jens Theisen

Jens said:
Uh? I'm not sure if I understand exactly what you mean.

From the other branch I conclude that you probably mean something like
boost's pointer containers, which are best discribed as smart containers.

If that's the case, I can't see how I can safely extract a value from
the container, since the memory management is bound to the container.

Jens
 
A

AlesD

Kai-Uwe Bux napsal(a):
Pointers it is, however, you can make your life easier using smart pointers.
If you want to keep copy semantics, you should use a cloning smart pointer
or a copy smart pointer. Google this group for those terms and you will
find code. If you are happy with reference count base reference semantics,
you can use tr1::shared_ptr. In either case, the compiler provided copy
constructors and assignment operators for classes that contain a

std::my_list< well_chosen_smart_pointer< MyClass > >

will work fine.


Best

Kai-Uwe Bux

Thanks for suggestions.

The problem is that I need deep copy of the std::list<MyClass *>
because I do not want to objects owning that list modify each other's
contents. I'll start with the wrapper and maybe write my own container
later.

AlesD
 
K

Kai-Uwe Bux

AlesD said:
Kai-Uwe Bux napsal(a):

Thanks for suggestions.

The problem is that I need deep copy of the std::list<MyClass *>
because I do not want to objects owning that list modify each other's
contents. I'll start with the wrapper and maybe write my own container
later.

Then, you could use smart pointers with deep copy semantics. Google for
copy_ptr or clone_ptr. The following thread provides a simple
implementation:

http://groups.google.com/group/comp..._frm/thread/cfd4b918d8a94885/03ffab1d1b9df8d7



Best

Kai-Uwe Bux
 
M

marius lazer

red said:
OK, what's the difference?

One cannot define a polymorphic STL container of smart pointers. Smart
pointers do not carry the polymorphic traits of the types they wrap;
they become completely new types. They are useful though for
non-polymorphic (uniform) pointer containers.

class B : public A {};
smart_ptr<B> and smart_ptr<A> are *unrelated*.

Marius
 
K

Kai-Uwe Bux

marius said:
One cannot define a polymorphic STL container of smart pointers. Smart
pointers do not carry the polymorphic traits of the types they wrap;
they become completely new types. They are useful though for
non-polymorphic (uniform) pointer containers.

class B : public A {};
smart_ptr<B> and smart_ptr<A> are *unrelated*.

That is not necessarily true. If B derives from A, then an assignment

A* a_ptr;
B* b_ptr;
a_ptr = b_ptr;

makes sense wheread

b_ptr = a_ptr;

requires a cast. There is not intrinsic reason, why smart pointers could not
implement this. Below, you find a simple proof of concept with a reference
counted shared pointer. The same thing can easily be done for a smart
pointer with deep copy semantics.

However, there is a good reason why one usually would not bother
implementing this in a smart pointer: the allocation idiom

smart_ptr<Base> t_ptr ( new Derived ( ... ) );

will usually provide enough polymorphism.


// Proof of concept
// ================

#include <algorithm>
#include <functional>

template < typename T >
class refcount_ptr;

template < typename T >
void swap ( refcount_ptr< T > &, refcount_ptr< T > & );

template < typename D, typename T >
refcount_ptr<D> up_cast_dynamic ( refcount_ptr<T> const & t_ptr );

template < typename D, typename T >
refcount_ptr<D> up_cast_static ( refcount_ptr<T> const & t_ptr );

template < typename T >
class refcount_ptr {

friend void swap<> ( refcount_ptr<T> &, refcount_ptr<T> & );

template < typename D, typename S >
friend
refcount_ptr<D> up_cast_dynamic ( refcount_ptr<S> const & );

template < typename D, typename S >
friend
refcount_ptr<D> up_cast_static ( refcount_ptr<S> const & );

template < typename S >
friend class refcount_ptr;

unsigned long* c_ptr;
T * t_ptr;

template < typename B >
refcount_ptr ( refcount_ptr<B> const & other, int )
: c_ptr ( other.c_ptr )
, t_ptr ( dynamic_cast< T* >( other.t_ptr ) )
{
++ (*c_ptr);
}

template < typename B >
refcount_ptr ( refcount_ptr<B> const & other, bool )
: c_ptr ( other.c_ptr )
, t_ptr ( static_cast< T* >( other.t_ptr ) )
{
++ (*c_ptr);
}

public:

refcount_ptr ( T * ptr = 0 )
: c_ptr( new unsigned long ( 1 ) )
, t_ptr( ptr )
{}

refcount_ptr ( refcount_ptr const & other )
: c_ptr ( other.c_ptr )
, t_ptr ( other.t_ptr )
{
++ (*c_ptr);
}

template < typename D >
refcount_ptr ( refcount_ptr<D> const & other )
: c_ptr ( other.c_ptr )
, t_ptr ( other.t_ptr )
{
++ (*c_ptr);
}

~refcount_ptr ( void ) {
-- (*c_ptr);
if ( (*c_ptr) == 0 ) {
delete( c_ptr );
delete( t_ptr );
}
}

refcount_ptr & operator= ( refcount_ptr const & other ) {
refcount_ptr tmp ( other );
swap( *this, tmp );
return( *this );
}

template < typename D >
refcount_ptr & operator= ( refcount_ptr<D> const & other ) {
refcount_ptr tmp ( other );
swap( *this, tmp );
return( *this );
}

T const * operator-> ( void ) const {
return( t_ptr );
}

T * operator-> ( void ) {
return( t_ptr );
}

T const & operator* ( void ) const {
return( *( this->operator->() ) );
}

T & operator* ( void ) {
return( *( this->operator->() ) );
}

bool operator== ( refcount_ptr const & other ) const {
return ( this->t_ptr == other.t_ptr );
}

bool operator!= ( refcount_ptr const & other ) const {
return ( this->t_ptr != other.t_ptr );
}

bool operator< ( refcount_ptr const & other ) const {
return ( std::less<T*>( this->t_ptr, other.t_ptr ) );
}

bool operator<= ( refcount_ptr const & other ) const {
return ( std::less_equal<T*>( this->t_ptr, other.t_ptr ) );
}

bool operator> ( refcount_ptr const & other ) const {
return ( std::greater<T*>( this->t_ptr, other.t_ptr ) );
}

bool operator>= ( refcount_ptr const & other ) const {
return ( std::greater_equal<T*>( this->t_ptr, other.t_ptr ) );
}

};

template < typename T >
void swap ( refcount_ptr< T > & p, refcount_ptr< T > & q ) {
std::swap( p.c_ptr, q.c_ptr );
std::swap( p.t_ptr, q.t_ptr );
}

template < typename D, typename T >
refcount_ptr<D> up_cast_dynamic ( refcount_ptr<T> const & p ) {
return ( refcount_ptr<D>( p, 1 ) );
}

template < typename D, typename T >
refcount_ptr<D> up_cast_static ( refcount_ptr<T> const & p ) {
return ( refcount_ptr<D>( p, true ) );
}



#include <iostream>

struct Base {

Base ( void ) {
std::cout << "base is born.\n";
}

Base ( Base const & other ) {
std::cout << "base is copied.\n";
}

virtual ~Base () {
std::cout << "base dies.\n";
}

virtual
std::eek:stream & dump ( std::eek:stream & ostr ) const {
return( ostr << "base\n" );
}

};

std::eek:stream & operator<< ( std::eek:stream & ostr,
Base const & obj ) {
return( obj.dump( ostr ) );
}

struct Derived : public Base {

Derived ( void ) {
std::cout << "derived is born.\n";
}

Derived ( Derived const & other )
: Base ( other )
{
std::cout << "derived is copied.\n";
}

virtual ~Derived () {
std::cout << "derived dies.\n";
}

virtual
std::eek:stream & dump ( std::eek:stream & ostr ) const {
return( ostr << "derived\n" );
}

};

struct Unrelated {

Unrelated ( void ) {
std::cout << "derived is born.\n";
}

Unrelated ( Unrelated const & other )
{
std::cout << "derived is copied.\n";
}

virtual ~Unrelated () {
std::cout << "derived dies.\n";
}

virtual
std::eek:stream & dump ( std::eek:stream & ostr ) const {
return( ostr << "unrelated\n" );
}

};

int main ( void ) {
refcount_ptr< Base > a_ptr ( new Base() );
refcount_ptr< Base > b_ptr ( new Derived() );

refcount_ptr< Derived > d_ptr ( new Derived() );
refcount_ptr< Base > c_ptr ( d_ptr );

refcount_ptr< Derived > e_ptr;

d_ptr->dump( std::cout );
c_ptr->dump( std::cout );

a_ptr->dump ( std::cout );
a_ptr = d_ptr;
a_ptr->dump( std::cout );
b_ptr->dump( std::cout );

// uncommenting the following yields a compile time error:
/*
refcount_ptr< Unrelated > u_ptr;
b_ptr = u_ptr;
*/
e_ptr = up_cast_dynamic< Derived >( a_ptr );
e_ptr->dump( std::cout );

a_ptr = refcount_ptr<Base>();
std::cout << "first handle deleted.\n";
b_ptr = refcount_ptr<Base>();
std::cout << "second handle deleted.\n";
c_ptr = refcount_ptr<Base>();
std::cout << "third handle deleted.\n";
d_ptr = refcount_ptr<Derived>();
e_ptr = refcount_ptr<Derived>();
}


Sorry for the long post.

Kai-Uwe Bux
 
M

marius lazer

Kai-Uwe Bux said:
That is not necessarily true. If B derives from A, then an assignment

A* a_ptr;
B* b_ptr;
a_ptr = b_ptr;

makes sense wheread

b_ptr = a_ptr;

requires a cast. There is not intrinsic reason, why smart pointers could not
implement this. Below, you find a simple proof of concept with a reference
counted shared pointer. The same thing can easily be done for a smart
pointer with deep copy semantics.

However, there is a good reason why one usually would not bother
implementing this in a smart pointer: the allocation idiom

I should have stated STL or TR1 smart pointers. With custom solutions
we can do almost everything.

Marius
 
P

peter koch

marius said:
I should have stated STL or TR1 smart pointers. With custom solutions
we can do almost everything.

Are you sure? I am quite confident that shared_ptr<derived> can be
assigned to a shared_ptr<base> (not the other way around, of course).

/Peter
 
T

Thomas J. Gritzan

peter said:
Are you sure? I am quite confident that shared_ptr<derived> can be
assigned to a shared_ptr<base> (not the other way around, of course).

*me too*

"shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T*
can be implicitly converted to U*. In particular, shared_ptr<T> is
implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is
an accessible base of T, and to shared_ptr<void>."

http://www.boost.org/libs/smart_ptr/shared_ptr.htm
 
M

marius lazer

Thomas said:
*me too*

"shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T*
can be implicitly converted to U*. In particular, shared_ptr<T> is
implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is
an accessible base of T, and to shared_ptr<void>."

Sorry, my bad (I'm not using shared_ptr). Then my previous statement is
also incorrect: polymorphic containers can be 100% implemented using
shared_ptr instead of raw pointers.

Marius
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top