Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing object ownership in C++

Tags:

c++

What is the best way to indicate that an object wants to take ownership of another object? So far, I've been using a std::auto_ptr in the public interface, so the client knows that the interface wants to take ownership of the passed object.

However, the latest GCC tells me auto_ptr is deprecated, so I wonder what is recommended? boost::interprocess::unique_pointer looks like a good candidate, but is this really the best solution out there?

like image 995
Anteru Avatar asked Jan 13 '09 09:01

Anteru


People also ask

How do I transfer ownership of unique PTRS?

In C++11 we can transfer the ownership of an object to another unique_ptr using std::move() . After the ownership transfer, the smart pointer that ceded the ownership becomes null and get() returns nullptr.

What is ownership in C++?

An owner is an object containing a pointer to an object allocated by new for which a delete is required. Every object on the free store (heap, dynamic store) must have exactly one owner. If there are two pointers to an object on the free store, only one can be the owner.

How are objects passed C++?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.


1 Answers

boost::interprocess is a library for interprocess communication, so I wouldn't use it for different purposes.

As discussed on this forum:

http://objectmix.com/c/113487-std-auto_ptr-deprecated.html

std::auto_ptr will be declared deprecated in the next version of the standard, where it will be recommended the usage of std::unique_ptr, which requires rvalue references and move semantics to be implemented (that's a fairly complicated feature).

Until the new standard is released, I would simply try to disable the warning if possible, or ignore it, for maximum portability.

If you want to already switch to the next language standard, it is possible since rvalue references have been implemented (see http://russ.yanofsky.org/rref/), so also std::unique_ptr should be supported.

On of the advantages of the new semantics is that you can pass to the move constructor also a temporary or any rvalue; in other cases, this allows avoiding to copy (for instance) objects contained inside a std::vector (during reallocation) before destroying the original ones.

like image 149
Blaisorblade Avatar answered Oct 12 '22 11:10

Blaisorblade