Overview
Features
Download
Documentation
Community
Add-Ons & Services

How to properly use AutoPtr/SharedPtr

A general discussion forum.

How to properly use AutoPtr/SharedPtr

Postby jorgeas80 » 29 May 2014, 15:09

Hello,

I'm building a C++ library using POCO C++, and I'm using AutoPtr / SharedPtr to handle pointers. But I have a doubt about the proper use of these classes.

Scenario: A class holding a vector of pointers to objects implementing reference counting. How should I declare this vector?

  • std::vector<MyRefCountingClass *> myVector;
  • std::vector <AutoPtr<MyRefCountingClass>> myVector;

If I choose the first option, I can have a problem if:

  1. A user creates a new MyRefCountingClass instance using AutoPtr
  2. That user stores the created reference in my vector (so, I'm assigning an AutoPtr to a normal pointer).
  3. The user gets that element from the vector, and store the result in a different AutoPtr (now, the first AutoPtr and this one both claim the ownership of the object)

If in the step 3 I explicitly tell AutoPtr that it has to share ownership of the object (sharing = true or assign method of AutoPtr), I'd solve the problem, but it doesn't sound elegant to me. For that reason, I'd go with option 2: declaring my vector as holding AutoPtr instead of normal pointers.

Am I right with this approach?

Many thanks in advance
jorgeas80
 
Posts: 10
Joined: 11 Apr 2014, 15:06

Re: How to properly use AutoPtr/SharedPtr

Postby guenter » 30 May 2014, 17:59

Option 2 (std::vector<Poco::AutoPtr<RCC> >) is the correct one.
guenter
 
Posts: 1119
Joined: 11 Jul 2006, 16:27
Location: Austria

Re: How to properly use AutoPtr/SharedPtr

Postby jorgeas80 » 30 May 2014, 18:50

Good to know. Many thanks!
jorgeas80
 
Posts: 10
Joined: 11 Apr 2014, 15:06


Return to General Discussion

Who is online

Users browsing this forum: No registered users and 1 guest