468,503 Members | 2,214 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,503 developers. It's quick & easy.

Slicing instances in STL containers

Hello,

I have problem that when I use std::list<MyClassand 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
Aug 28 '06 #1
19 3149
AlesD wrote:
Hello,

I have problem that when I use std::list<MyClassand 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

Aug 28 '06 #2
On Mon, 28 Aug 2006 07:36:13 -0400, Kai-Uwe Bux <jk********@gmx.net>
wrote:
>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
Aug 28 '06 #3
Roland Pibinger wrote:
>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?

Aug 28 '06 #4
Roland Pibinger wrote:
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
Aug 28 '06 #5
Roland Pibinger wrote:
On Mon, 28 Aug 2006 07:36:13 -0400, Kai-Uwe Bux <jk********@gmx.net>
wrote:
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.
Could you please explain what you mean by mismatch, and--if
possible--provide an alternate solution that avoids it?

Aug 28 '06 #6
On Mon, 28 Aug 2006 17:26:03 GMT, red floyd <no*****@here.dudewrote:
>Roland Pibinger wrote:
>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
Aug 28 '06 #7
On Mon, 28 Aug 2006 19:20:11 +0100, Jens Theisen <jt***@arcor.de>
wrote:
>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
Aug 28 '06 #8
On 28 Aug 2006 12:22:23 -0700, "Squeamizh" <sq*****@hotmail.com>
wrote:
>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
Aug 28 '06 #9
Roland Pibinger wrote:
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
Aug 28 '06 #10
Jens Theisen wrote:
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
Aug 28 '06 #11
Kai-Uwe Bux napsal(a):
AlesD wrote:
>>
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>

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
Aug 28 '06 #12
Roland Pibinger wrote:
>

Someone with your skill set can write a container for pointers (real
pointers, of course, not "smart" pointers).
OK, what's the difference?
Aug 29 '06 #13
AlesD wrote:
Kai-Uwe Bux napsal(a):
>AlesD wrote:
>>>
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>

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.
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....ffab1d1b9df8d7

Best

Kai-Uwe Bux

Aug 29 '06 #14

red floyd wrote:
Roland Pibinger wrote:


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

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<Band smart_ptr<Aare *unrelated*.

Marius

Aug 29 '06 #15
marius lazer wrote:
>
red floyd wrote:
>Roland Pibinger wrote:
>

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

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<Band smart_ptr<Aare *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<Baset_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<Dup_cast_dynamic ( refcount_ptr<Tconst & t_ptr );

template < typename D, typename T >
refcount_ptr<Dup_cast_static ( refcount_ptr<Tconst & 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<Dup_cast_dynamic ( refcount_ptr<Sconst & );

template < typename D, typename S >
friend
refcount_ptr<Dup_cast_static ( refcount_ptr<Sconst & );

template < typename S >
friend class refcount_ptr;

unsigned long* c_ptr;
T * t_ptr;

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

template < typename B >
refcount_ptr ( refcount_ptr<Bconst & 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<Dconst & 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<Dconst & 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<Dup_cast_dynamic ( refcount_ptr<Tconst & p ) {
return ( refcount_ptr<D>( p, 1 ) );
}

template < typename D, typename T >
refcount_ptr<Dup_cast_static ( refcount_ptr<Tconst & 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::ostream & dump ( std::ostream & ostr ) const {
return( ostr << "base\n" );
}

};

std::ostream & operator<< ( std::ostream & 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::ostream & dump ( std::ostream & 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::ostream & dump ( std::ostream & 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
Aug 30 '06 #16

Kai-Uwe Bux wrote:
marius lazer wrote:

red floyd wrote:
Roland Pibinger wrote:
Someone with your skill set can write a container for pointers (real
pointers, of course, not "smart" pointers).


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<Band smart_ptr<Aare *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
I should have stated STL or TR1 smart pointers. With custom solutions
we can do almost everything.

Marius

Aug 30 '06 #17

marius lazer wrote:
Kai-Uwe Bux wrote:
marius lazer wrote:
>
red floyd wrote:
>Roland Pibinger wrote:
>
>
Someone with your skill set can write a container for pointers (real
pointers, of course, not "smart" pointers).
>
>>
>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<Band smart_ptr<Aare *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

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<derivedcan be
assigned to a shared_ptr<base(not the other way around, of course).

/Peter

Aug 30 '06 #18
peter koch schrieb:
marius lazer wrote:
>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<derivedcan be
assigned to a shared_ptr<base(not the other way around, of course).
*me too*

"shared_ptr<Tcan be implicitly converted to shared_ptr<U whenever T*
can be implicitly converted to U*. In particular, shared_ptr<Tis
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

--
Thomas
Aug 30 '06 #19

Thomas J. Gritzan wrote:
peter koch schrieb:
marius lazer wrote:
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<derivedcan be
assigned to a shared_ptr<base(not the other way around, of course).

*me too*

"shared_ptr<Tcan be implicitly converted to shared_ptr<U whenever T*
can be implicitly converted to U*. In particular, shared_ptr<Tis
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

Aug 30 '06 #20

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Jerry Sievers | last post: by
3 posts views Thread by Bryan Olson | last post: by
17 posts views Thread by Jon Slaughter | last post: by
17 posts views Thread by baibaichen | last post: by
1 post views Thread by Bart Simpson | last post: by
2 posts views Thread by Rahul | last post: by
1 post views Thread by subramanian100in | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.