473,804 Members | 2,271 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Slicing instances in STL containers

Hello,

I have problem that when I use std::list<MyCla ssand 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<MyCla ss>
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
19 3408
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<MyCla ss>

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_sma rt_pointer< MyClass

will work fine.
Best

Kai-Uwe Bux
Thanks for suggestions.

The problem is that I need deep copy of the std::list<MyCla ss *>
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<MyCla ss>

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_sma rt_pointer< MyClass

will work fine.
Best

Kai-Uwe Bux

Thanks for suggestions.

The problem is that I need deep copy of the std::list<MyCla ss *>
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<Du p_cast_dynamic ( refcount_ptr<Tc onst & t_ptr );

template < typename D, typename T >
refcount_ptr<Du p_cast_static ( refcount_ptr<Tc onst & 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<Du p_cast_dynamic ( refcount_ptr<Sc onst & );

template < typename D, typename S >
friend
refcount_ptr<Du p_cast_static ( refcount_ptr<Sc onst & );

template < typename S >
friend class refcount_ptr;

unsigned long* c_ptr;
T * t_ptr;

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

template < typename B >
refcount_ptr ( refcount_ptr<Bc onst & 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<Dc onst & 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<Dc onst & 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_eq ual<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<Du p_cast_dynamic ( refcount_ptr<Tc onst & p ) {
return ( refcount_ptr<D> ( p, 1 ) );
}

template < typename D, typename T >
refcount_ptr<Du p_cast_static ( refcount_ptr<Tc onst & 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<Ba se>();
std::cout << "first handle deleted.\n";
b_ptr = refcount_ptr<Ba se>();
std::cout << "second handle deleted.\n";
c_ptr = refcount_ptr<Ba se>();
std::cout << "third handle deleted.\n";
d_ptr = refcount_ptr<De rived>();
e_ptr = refcount_ptr<De rived>();
}
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<deri vedcan 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<deri vedcan be
assigned to a shared_ptr<base (not the other way around, of course).
*me too*

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

*me too*

"shared_ptr<Tca n 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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
3258
by: hokiegal99 | last post by:
How would I determine if a filename is greater than a certain number of characters and then truncate it to that number? For example a file named XXXXXXXXX.txt would become XXXXXX fname = files if fname > 6 print fname Thanks!!!
9
2478
by: Jerry Sievers | last post by:
Fellow Pythonists; I am totally puzzled on the use of slicing on mapping types and especially unsure on use of the Ellipsis... and slicing syntax that has two or more groups seperated by comma. I am referring to (from the manual); Slice objects Slice objects are used to represent slices when extended
3
2062
by: Bryan Olson | last post by:
I recently wrote a module supporting value-shared slicing. I don't know if this functionality already existed somewhere, but I think it's useful enough that other Pythoners might want it, so here it is. Also, my recent notes on Python warts with respect to negative indexes were based on problems I encoutered debugging this module, so I'm posting it partially as a concrete example of what I was talking about.
11
2057
by: jbperez808 | last post by:
>>> rs='AUGCUAGACGUGGAGUAG' >>> rs='GAG' Traceback (most recent call last): File "<pyshell#119>", line 1, in ? rs='GAG' TypeError: object doesn't support slice assignment You can't assign to a section of a sliced string in Python 2.3 and there doesn't seem to be mention of this as a Python 2.4 feature (don't have time to actually try
17
16631
by: Jon Slaughter | last post by:
I'm having a little trouble understanding what the slicing problem is. In B.S.'s C++ PL3rdEd he says "Becayse the Employee copy functions do not know anything about Managers, only the Employee part of Manager is copied. ".... and gives the code above as .....
17
3579
by: baibaichen | last post by:
i have written some code to verify how to disable slicing copy according C++ Gotchas item 30 the follow is my class hierarchy, and note that B is abstract class!! class B { public: explicit B(INT32 i =0):i_(i){} virtual ~B(){}
1
3477
by: Bart Simpson | last post by:
Can anyone explain the concept of "slicing" with respect to the "virtual constructor" idiom as explain at parashift ? From parashift: class Shape { public: virtual ~Shape() { } // A virtual destructor
2
4709
by: Rahul | last post by:
Hi Everyone, I was working around object slicing (pass by value) and was wondering how it is specified in the standard, class A { }; class B: public A
1
2795
by: subramanian100in | last post by:
Consider class Base { .... }; class Derived : public Base { ...
0
10599
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10346
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9173
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.