On 12/16/2016 06:56 PM, Jakub Jelinek wrote:
> On Fri, Dec 16, 2016 at 06:52:03PM +0000, Pedro Alves wrote:
>> GDB has a string_printf function that prints into a std::string, for
>> example.  Like:
>>
>>   std::string hello = string_printf ("%s", "hello world");
>>
>> That's a function that many C++ projects reinvent.
> 
> If you then want to work with it as std::string object, sure, it makes
> sense.  But if all you want is to pass the string to %s of another
> formatting function and free it, then going through std::string
> doesn't add many benefits over just xasprintf + free.

It has all the usual advantages of RAII.  
It completely eliminates the "forgot to call free in this
exit path" bug by design.

And then there's exception safety, in case something throws
beforeyou reach the "+ free".

(I know GCC doesn't use exceptions; GDB does.  But do note
https://gcc.gnu.org/codingrationale.html says:

 We would like the compiler to be exception safe, to permit
 reconsideration of the exception convention. This change
 would require a significant change in style,
 adopting "resource acquisition is initialization" (RAII). We would be 
 using shared_ptr (from TR1's <memory>) or unique_ptr (from C++11).
)

We've started using RAII objects in GDB in the past couple
months, including C++11 unique_ptr, and that has already
simplified the codebase a good deal, and fixed many leaks
and bugs.

Thanks,
Pedro Alves

Reply via email to