[vtk-developers] smart pointer & type checking

Brad King brad.king at kitware.com
Wed Mar 19 09:07:48 EDT 2008


Utkarsh Ayachit wrote:
> Shead, Timothy wrote:
>> On 3/18/08 3:56 PM, "clinton at elemtech.com" <clinton at elemtech.com> wrote:
>>
>>>
>>> So why does this even compile?  I'd prefer to get a compile error.
>>>
>>>  vtkSmartPointer<vtkPolyData> MyPolyData =
>>>    vtkSmartPointer<vtkMultiBlockDataSet>::New();
>>
>> Amazingly spooky ... I just got bitten by this a few minutes ago!  Not
>> only
>> is it not a compile error, it isn't a runtime error either ...
> Because of this:
>
> class vtkSmartPointerBase
> {
> ...
>   vtkSmartPointerBase& operator=(const vtkSmartPointerBase& r);
> ...
> }
>
> May be this operator should be defined in the subclass to avoid such a
> behaviour.

Actually it's this constructor and assignment operator in the subclass:

  vtkSmartPointer(const vtkSmartPointerBase& r);
  vtkSmartPointer& operator=(const vtkSmartPointerBase& r);

This is a consequence of the way vtkSmartPointer is implemented to deal
with derived-to-base conversions on broken compilers that don't support
member templates.  Correct code compiles but unfortunately some
incorrect code does too.

The constructor should actually have a signature like

 public:
  template <class U>
  vtkSmartPointer(vtkSmartPointer<U> const& r):
    vtkSmartPointerBase(CheckType(r.GetPointer()) {}
 private:
  static T* CheckType(T* t) { return t; }

but it won't compile on old compilers.  If someone wants to use the
preprocessor to fix this for good compilers and leave the old code for
bad compilers, I encourage you to proceed.  You can test for member
template support like this:

  #include <vtksys/Configure.hxx>
  #if vtksys_CXX_HAS_MEMBER_TEMPLATES
    // has member templates
  #else
    // no member templates
  #endif

-Brad



More information about the vtk-developers mailing list