[Insight-users] Using non-smart pointers

Matt McCormick matt.mccormick at kitware.com
Fri Dec 2 10:53:22 EST 2011


Hi David,

Looking at itkMacro.h where the itkNewMacro is defined:

#define itkNewMacro(x)                                         \
  itkSimpleNewMacro(x)                                         \
  itkCreateAnotherMacro(x)

#define itkSimpleNewMacro(x)                                   \
  static Pointer New(void)                                     \
    {                                                          \
    Pointer smartPtr = ::itk::ObjectFactory< x >::Create();    \
    if ( smartPtr.GetPointer() == NULL )                       \
      {                                                        \
      smartPtr = new x;                                        \
      }                                                        \
    smartPtr->UnRegister();                                    \
    return smartPtr;                                           \
    }

So the ::New() creates a "Pointer" by default (itk::SmartPointer), and
it calls UnRegister() before it returns.  So, you must assign to a
SmartPointer, or the reference count goes to zero and the object is
destroyed.

Thanks,
Matt

On Fri, Dec 2, 2011 at 10:42 AM, David Doria <daviddoria at gmail.com> wrote:
> If I have a function like this:
>
> void Test(const ImageType* input, ImageType* output)
>
> and I create 'output' like this:
>
> ImageType::Pointer outputImage = ImageType::New();
> void Test(input, outputImage);
>
> all is well. However, if I do this:
>
> ImageType* outputImage = ImageType::New();
> void Test(input, outputImage);
>
> it segfaults when I try to use 'output'. Here is a demonstration of
> the problem: http://www.itk.org/Wiki/ITK/Examples/Broken/Utilities/NonSmartPointers
>
> Can anyone explain what is wrong with this?
>
> Thanks,
>
> David
> _____________________________________
> Powered by www.kitware.com
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>
> Kitware offers ITK Training Courses, for more information visit:
> http://www.kitware.com/products/protraining.html
>
> Please keep messages on-topic and check the ITK FAQ at:
> http://www.itk.org/Wiki/ITK_FAQ
>
> Follow this link to subscribe/unsubscribe:
> http://www.itk.org/mailman/listinfo/insight-users


More information about the Insight-users mailing list