I'm updating some pre c++11 code to use c++11 unique_ptrs.
One thing I'm unsure how to handle is when the old code was using pointer assignment as a condition. E.g.
Object* obj;
while ( obj = C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() )
{
// do something with obj
delete obj;
}
Given that std::unique_ptr::reset has no return value, it's not possible to translate this directly to:
std::unique_ptr< Object > obj;
while ( obj.reset( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() ) )
{
// do something with obj
}
So, what's the cleanest way to upgrade this code to use unique_ptrs? The best I can come up with is:
std::unique_ptr< Object > obj;
obj.reset( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() );
while ( obj )
{
// do something with obj
obj.reset( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() );
}
But that adds the messy double call to the library function, which ideally I'd like to avoid.
How about:
while ( auto obj = std::unique_ptr<Object>( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() ) )
{
// do something with obj
}
If you want to keep obj
alive outside the loop, you can use the comma operator:
std::unique_ptr< Object > obj;
while ( obj.reset( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() ), obj )
{
// do something with obj
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With