39912

convert pointer to shared_ptr

Question:

I have some library code (I cannot not change the source code) that returns a pointer to an object (B). I would like to store this pointer as shared_ptr under a class with this type of constructor:

class A { public: A(boost::shared_ptr<B> val); ... private: boost::shared_ptr<B> _val; ... }; int main() { B *b = SomeLib(); A a(b); //?? delete b; ... }

That is, I would like to make a deep-copy of b and control its life-time under a (even if original b is deleted (delete b), I still have an exact copy under a).

I'm new to this, sorry if it seems trivial...

Answer1:

As you say, you have to copy them not just copy a pointer. So either B already has implemented 'clone' method or you have to implement some external B* copy(B* b) which will create new B with same state.

In case B has implemented copy constructor you can implement copy as just

B* copyOf(B* b) { return new B(*b); }

In case B has implemented <a href="http://en.wikipedia.org/wiki/Prototype_pattern" rel="nofollow">clone method or similar</a> you can implement copy as

B* copyOf(B* b) { return b->clone(); }

and then your code will look like

int main() { B *b = SomeLib(); A a(copyOf(b)); delete b; ... }

Answer2:

If the library defines this B object, the library should provide (or outright prohibit) the mechanism for copying B.

As a sidenote,

If your class A is exclusively controlling the lifetime of this copied object, the smart pointer you really want to use is boost::scoped_ptr.

boost::shared_ptr is named after its ability to share lifetime responsibility, which it sounds like you don't want. scoped_ptr won't let that accidentally happen.

Answer3:

Deep-copying is implemented trivially in C++ by the copy constructor since in C++, <em>all</em> objects have value semantics by default. Copying in such a way doesn't work for polymorphous objects though – in such cases, you'd have to implement a virtually overridden clone method in your class.

But in all other cases, simply writing

A(boost::shared_ptr<B> val) : _val(new B(*val)) { }

will do.

Recommend

  • Automaticaly copy native dll to the bin folder of referencing project in Visual Studio
  • Dropping support for JRE 1.3
  • Why dsofile.dll still need Office Installation?
  • Reusing the CQ5 Form into the mywebsite components is not showing up the End of the Form section
  • Renamed directory, now SVN not allowing me to commit
  • HTMLcollection 0 list length, [n] returns undefined, converting to an array returns an empty array
  • Duplicate Entries in DB
  • ZeroMQ poll thread safety
  • Theme in user control
  • initializing array of variable size inside a class
  • IP and domain create different session
  • Delete record on sepecific field value in liferay service builder
  • ReactJs.net server side render failing after publish
  • EF6 and pre-generated views
  • How to Translate texts contained in MsgBox in Inno Setup?
  • How to get to older Xcode beta version?
  • 'doc_del_count' bigger than 'doc_count' on CouchDB
  • Most efficient way to move table rows from one table to another
  • How can I get the choice “H2” back in the H2 consol?
  • Upload file that is in the cpan database
  • Who propagate bugfixes across branches (corporate development)?
  • xcode don't localize specific strings
  • std::remove_copy_if_ valgrind bytes in block are possibly lost in loss record
  • Functions in global context
  • ilmerge with a PFX file
  • Nant, Vault & Windows Integrated Authentication
  • Bug in WPF DataGrid
  • Does CUDA 5 support STL or THRUST inside the device code?
  • jQuery tmpl and DataLink beta
  • How can I estimate amount of memory left with calling System.gc()?
  • Delete MySQLi record without showing the id in the URL
  • GridView Sorting works once only
  • XCode can't find symbols for a specific iOS library/framework project
  • How do I rollback to a specific git commit
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android
  • Checking variable from a different class in C#
  • Running Map reduces the dimensions of the matrices