Gaga
Gaga

Reputation: 41

Is it a right way to use unique_ptr?

I have a raw pointer and would like to have the callback owns it. I come up with this code:

A* a = new A();
dosomething(callback(unique_ptr<A>(a).get()))

// The callback always takes a raw pointer.
void callback(A* a) {
}

Is it the right way to do?

Upvotes: 0

Views: 220

Answers (2)

David Haim
David Haim

Reputation: 26516

I would simplify the whole thing and use std::shared_ptr:

auto a = std::make_shared<A>();
callback(a);

this will require you to declare callback as one which gets std::shared_ptr at the first place.

of course, It's a bit odd that callback doesn't return anything..

Upvotes: 0

Alyssa Haroldsen
Alyssa Haroldsen

Reputation: 3731

No, callback doesn't own it. It will, however, be destroyed after dosomething finishes.

If you constructed dosomething to take a callback and an A *, then had dosomething call callback with the given A * as an argument, it could work as long as the unique_ptr created is only used during its execution.

Example:

void callback(A *a)
{
    if (!a) return;
    std::cout << "Got A " << a->name() << std::endl;
}

void dosomething(const std::function<void(A *)> &func, std::unique_ptr<A> obj)
{
    std::cout << "Doing some operation..." << std::endl;
    func(obj.get());
}

int main()
{
    dosomething(callback, std::make_unique<A>());
}

Upvotes: 1

Related Questions