I have a function that effectively does this
void foo(Class** c)
{
// memory checks and stuff
(*c) = new Class();
// more stuff
}
I cannot change this function. To call this function I have to do something like this.
Class* c = nullptr;
foo(&c);
if (c)
{
// stuff
}
delete c;
I would very much prefer to use a std::unique_ptr
rather than the raw pointer. However, I don't know how to get the address of the internal pointer. The listing below does not compile, obviously, because I'm trying to take the address of an rvalue.
std::unique_ptr<Class> c = nullptr;
foo(&(c.get()));
if (c)
{
// stuff
}
I realize I could make the raw pointer as well as the unique pointer, call the function, then give the raw pointer to the unique pointer, but I would prefer to not. Is there a way to do what I want to do?
Create a wrapper around foo
:
std::unique_ptr<Class> foo()
{
Class* c = nullptr;
foo(&c);
return std::unique_ptr<Class>(c);
}
Your hands are tied by the API of the function.
The best solution I personally see is to do what you said you'd rather not: create the unique_ptr after calling the function.
If you call this function a lot or if you have many functions like it I would create a wrapper function that creates locally the raw pointer and returns unique_ptr.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.