VTK - Dynamic Memory Allocation

VTK - Dynamic Memory Allocation

vtkNew

vtkNew is a macro provided by VTK to create objects on the stack (automatic storage) instead of using dynamic memory allocation. It simplifies memory management and ensures that the objects are automatically deleted when they go out of scope, avoiding memory leaks. vtkNew is typically used for creating objects with local scope within functions or limited contexts.

Usage example - C++

vtkNew<vtkPolyDataMapper> mapper;

mapper->SetInputData(somePolyData);

Benefits:

  • Simple and convenient syntax for creating objects on the stack.
  • Automatic cleanup of objects when they go out of scope, reducing the chances of memory leaks.

Drawbacks:

  • Since vtkNew objects are created on the stack, they have a limited scope and can't be shared between different functions or objects.

vtkSmartPointer

vtkSmartPointer is a smart pointer class in VTK that provides automatic memory management for VTK objects on the heap (dynamic storage). It uses reference counting to keep track of how many smart pointers point to a particular object, and when the last smart pointer goes out of scope or is explicitly set to null, the associated object is deleted. vtkSmartPointer allows you to manage VTK objects' lifetimes dynamically, and they can be shared across different parts of your code.

Usage example - C++

vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();

mapper->SetInputData(somePolyData);


要查看或添加评论,请登录

Lahiru Dilshan的更多文章

社区洞察

其他会员也浏览了