Shivahn wrote:Ok, cool. I have a question though. Is this acceptable?
No. Never do that.
Just to clarify, it's not incorrect
, just a bad idea, at least if those mean something different to you.
The fact that fun
takes a normal pointer but then puts it into a unique_ptr is essentially the same as if it took the normal pointer and manually called delete. So let's just take that case.
The problem is that you've taken something which is very much part of the interface
of a function ("I delete my parameter") and put it solely in the implementation and (hopefully) documentation. This means it's easy to make the sort of mistake that Sc4Freak points out, where you pass a pointer to something that can't be deleted. (The group I'm in has had a couple occurrences of similar bugs.)
Making the unique_ptr be what's actually passed as the parameter takes the interface fact "I delete my parameter" and actually promotes that to be part of the signature
of the function -- which means the compiler can start to do checking for you.
It still won't prevent errors:
Code: Select all
fun(unique_ptr<Foo>(&x)); // bad doggy but the compiler will be happy
but it will tend to make them a lot more obvious. In the case of those two lines, I can tell you that there's an error without knowing anything about the implementation of fun.
Now, that's not to say you'll never write a function that takes a raw pointer and takes ownership of it eventually to delete it and have it be a good idea... it's theoretically possible. But... it won't be remotely common in C++.