Reputation: 51
There is an equivalent codification in C++ with smartpointers for this code?
In External.cpp:
class ExampleClass {...};
ExampleClass* function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return ptr;
}
In Another.cpp i would like to do something like this properly, how?:
ExampleClass *ptr2 = function();
Upvotes: 1
Views: 185
Reputation: 170153
I won't really recommend it, but you can return an object that implicitly converts to a raw pointer. It will own it for a short duration, and delete if no-one grabs it.
struct RelinquishOrDelete {
ExampleClass *_ptr;
operator ExampleClass*() { auto ret = _ptr; _ptr = nullptr; return ret; }
~RelinquishOrDelete() {
if(!_ptr) {
cerr << "returned object wasn't taken by a new owner\n";
delete _ptr;
}
}
};
Using it is simple. It will pack and unpack the pointer in this simple case:
RelinquishOrDelete function()
{
ExampleClass *ptr = new ExampleClass();
ptr->doSomething();
return {ptr};
}
// ...
ExampleClass *ptr2 = function();
But of course, it will likely cause unexpected behavior if used in this perfectly reasonable piece of code:
auto ptr3 = function();
A smart pointer with much stricter ownership semantics is really the best approach.
Upvotes: 1
Reputation: 3068
There are two actually, you could use either unique_ptr or shared_ptr, look here when to use which: Which kind of pointer do I use when?
I'f you'd opt for the unique_ptr, then you'd get:
class ExampleClass {...};
std::unique_ptr<ExampleClass> function()
{
std::unique_ptr<ExampleClass> uptr = std::make_unique<ExampleClass>();
uptr->doSomething();
return std::move(uptr);
}
//In Another.cpp
std::unique_ptr<ExampleClass> ptr2 = function();
//you could even store the result in a shared pointer!!
std::shared_ptr<ExampleClass> ptr3 = function();
Upvotes: 5