locked
Is it important to initialize smart pointers before use?

    Question

  • Are C++/CX smart pointers always initialized to nullptr? For example, if I declare a member variable:

    String^ foo;

    Then somewhere in my class I check for nullptr...

    if (!foo) foo = "bar";

    Will foo reliably be nullptr if I haven't set it yet? I know that normal pointers can contain garbage until they are explicitly set and am wondering if the same applies to smart pointers?

    Saturday, August 10, 2013 1:22 AM

Answers

  • Smart-pointers do a number of things that improve code quality:

    • They are always fully initialized
    • They automatically handle cleanup even in the presence of exceptions
    • They maintain clear object ownership rules (the details of which vary by smart-pointer)

    There are a few cases you have to be careful with them. For example, the common syntax with Microsoft::WRL::ComPtr when accepting a pointer would be something like:

    ComPtr obj;

    factory->CreateOjbect( &obj );

    If this is inline, this works fine. If you like it being a little wordier, you can use

    ComPtr obj;

    factory->CreateOjbect( obj.GetAddressOf() );

    If ComPtr obj is actually a member of a class, it's much safer to do the following to avoid leaks:

    factory->CreateOjbect( m_obj.ReleaseAndGetAddressOf() );


    Tuesday, August 13, 2013 7:33 AM

All replies

  • IMHO, pointers being what they are, I would never assume that they are in an initial state. They should be explicitly set. The main purpose of smart pointers is insure that its destructor is called, relieving the developer of that duty.

    http://msdn.microsoft.com/en-us/library/vstudio/hh279674.asp

    Saturday, August 10, 2013 2:18 PM
  • Smart-pointers generally always fully initialize themselves to avoid problems common to 'dumb pointers' like uninitialized variables which can result in very difficult to find heisenbugs.

    Tuesday, August 13, 2013 7:28 AM
  • Smart-pointers do a number of things that improve code quality:

    • They are always fully initialized
    • They automatically handle cleanup even in the presence of exceptions
    • They maintain clear object ownership rules (the details of which vary by smart-pointer)

    There are a few cases you have to be careful with them. For example, the common syntax with Microsoft::WRL::ComPtr when accepting a pointer would be something like:

    ComPtr obj;

    factory->CreateOjbect( &obj );

    If this is inline, this works fine. If you like it being a little wordier, you can use

    ComPtr obj;

    factory->CreateOjbect( obj.GetAddressOf() );

    If ComPtr obj is actually a member of a class, it's much safer to do the following to avoid leaks:

    factory->CreateOjbect( m_obj.ReleaseAndGetAddressOf() );


    Tuesday, August 13, 2013 7:33 AM