Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign smart pointer in condition or loop

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.

like image 995
ndawson Avatar asked Oct 18 '17 22:10

ndawson


2 Answers

How about:

while ( auto obj = std::unique_ptr<Object>( C_LIBRARY_CALL_WHICH_RETURNS_NEW_OBJECT() ) )
{
   // do something with obj
}
like image 50
Daniel Trugman Avatar answered Sep 20 '22 12:09

Daniel Trugman


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
}
like image 32
Joshua Green Avatar answered Sep 21 '22 12:09

Joshua Green