A stl vector of smart pointer

Y

yinglcs

In Effective STL item 8, it said 'Never create cointainers of
auto_ptrs'.

But in the Boost shared_ptr_example.cpp example, it creates a stl
vector of smart pointer.
Why it is okay in this case?

Here is part the code:
struct Foo
{
Foo( int _x ) : x(_x) {}
~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
int x;
/* ... */
};

typedef boost::shared_ptr<Foo> FooPtr;

struct FooPtrOps
{
bool operator()( const FooPtr & a, const FooPtr & b )
{ return a->x > b->x; }
void operator()( const FooPtr & a )
{ std::cout << a->x << "\n"; }
};

int main()
{
std::vector<FooPtr> foo_vector;
std::set<FooPtr,FooPtrOps> foo_set; // NOT multiset!

.... // omit
}
 
M

Mike Wahler

In Effective STL item 8, it said 'Never create cointainers of
auto_ptrs'.

But in the Boost shared_ptr_example.cpp example, it creates a stl
vector of smart pointer.

'auto_ptr' is one kind of 'smart pointer'. However, not
all 'smart pointers' are 'auto_ptr's,
Why it is okay in this case?

Find out why it's *not* OK with 'auto_ptr', and
I think you'll have your answer.

-Mike
 
V

Victor Bazarov

In Effective STL item 8, it said 'Never create cointainers of
auto_ptrs'.

But in the Boost shared_ptr_example.cpp example, it creates a stl
vector of smart pointer.
Why it is okay in this case?
[..]

Because 'std::auto_ptr' does not satisfy the requirement imposed on
the type of the contained items.

V
 
A

Axter

In Effective STL item 8, it said 'Never create cointainers of
auto_ptrs'.

But in the Boost shared_ptr_example.cpp example, it creates a stl
vector of smart pointer.
Why it is okay in this case?

Here is part the code:
struct Foo
{
Foo( int _x ) : x(_x) {}
~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
int x;
/* ... */
};

typedef boost::shared_ptr<Foo> FooPtr;

struct FooPtrOps
{
bool operator()( const FooPtr & a, const FooPtr & b )
{ return a->x > b->x; }
void operator()( const FooPtr & a )
{ std::cout << a->x << "\n"; }
};

int main()
{
std::vector<FooPtr> foo_vector;
std::set<FooPtr,FooPtrOps> foo_set; // NOT multiset!


You could avoid having to create a FooPtrOps type class, by using a
smart pointer like copy_ptr:
http://code.axter.com/copy_ptr.h

The above smart pointer uses value semantics for the comparison
operators.
std::set<copy_ptr<Foo> > foo_set;

You can also use a cow_ptr
http://code.axter.com/cow_ptr.h

Both the copy_ptr and the cow_ptr can clone the pointee when needed.
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top