Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for std::auto_ptr

I'm just getting used to smart pointers using std::auto_ptr.

Assume that I want to call a function with both auto_ptr and normal Pointers.

auto_ptr<uint32> data_smart(new uint32[123])]);
uint32 data_fix[123];
uint32* data_dumb = new uint32[123];

processData(data_smart);
processData(data_fix);
processData(data_dumb);

What is the best practice for this without overloading? Having the processData function with a uint32* argument? Can I cast the smart pointer to uint32* for this case with .get()? Or what is the way I should do it? Thanks in advance!

like image 790
vls Avatar asked May 27 '26 00:05

vls


2 Answers

1.

auto_ptr<uint32> data_smart(new uint32[123])]);

Don't do that. auto_ptr works with scalars only (it calls delete rather than delete[]).

2. auto_ptr owns the object it points to, so unless you want to pass the ownership to that function (in your code you don't), the function should accept a normal pointer. So you should change the call to:

processData(data_smart.get());

in order to explicitly express that data_smart continues to own the object.

like image 51
Yakov Galka Avatar answered May 28 '26 15:05

Yakov Galka


EDIT: Noah Roberts' comment on your question is the bigger issue here, but this answers the question asked even if the example code is wrong....


... without overloading ...

If you want to do it without overloading, the only option that's going to work for all of these is to make the method take a dumb pointer parameter.

Can I cast the smart pointer to uint32* for this case?

No. Use std::auto_ptr<t>::get().

like image 31
Billy ONeal Avatar answered May 28 '26 14:05

Billy ONeal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!