1
struct cls{
    ~cls(){std::cout<<"dtor\n";}
};

void foo(cls** pp){
    *pp = new cls;
}

int main()
{
    cls* raw_ptr = 0;    
    foo(&raw_ptr);
    std::unique_ptr<cls> u_ptr{raw_ptr};
}

Is there any way to directly access the raw_pointer in the unique_ptr to pass to the function foo(cls** pp)?

Or

cls* raw_ptr = 0;    
foo(&raw_ptr);
std::unique_ptr<cls> u_ptr{raw_ptr};

Is it the only way?

Note: I cannot change the signature of the function foo.

1

2 Answers 2

2

You can get read-only access to the pointer inside a unique_ptr by using unique_ptr::get(). This returns a copy of the pointer stored.

However, I understand your question as to whether there is a way to mutate the pointer in the unique_ptr in situ; here, the answer is no. You have to do the raw-to-unique dance you mention.

Of course, even if you can't change the signature of foo, you can certainly provide your own function to wrap that dance. It could even be an overload of foo:

std::unique_ptr<cls> foo()
{
  cls *p = nullptr;
  foo(&p);
  return std::unique_ptr<cls>{p};
}

[Live example]

Sign up to request clarification or add additional context in comments.

Comments

-1

unique_ptr<>::get() - it returns a pointer to the owned object, without releasing ownership of the object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.