-4

I create a vtkSmartPointer as a class variable and initialize it using:

imageStack = vtkSmartPointer<vtkImageData>::New();

would imageStack (a class variable) be allocated on the heap or the stack? I've read this post about using variable = new Object(); being on the heap, but is using ::New() any different?

Also, if imageStack is already pointing to memory with data in it, and I over write it by doing:

imageStack = vtkSmartPointer<vtkImageData>::New();

is it freeing the old memory it was pointing to prior? This post leads me to believe it is, but I still seem to be getting a stack overflow.

Lambda1010
  • 369
  • 2
  • 3
  • 13
  • 4
    If smart pointer was allocated on the heap then there would be a need for another smart pointer to manage pointer to first smart pointer... Depending on context `imageStack` can be allocated on the stack (if this is inside of function body) or on the heap (if this is a class field initialization). – user7860670 Jan 04 '19 at 22:07
  • 1
    The *variable* `imageStack` is automatic (best-guess by the entirely-incomplete sample you posted). Its behavior regarding [the assignment operator](https://www.vtk.org/doc/nightly/html/classvtkSmartPointer.html#a7a8b363f6f604735f5368d9c5577fda2) is also documented, which never hurts to check. If you want help with your stack overflow, present a [mcve] the presents it (stress minimal) and we may be able to help. – WhozCraig Jan 04 '19 at 22:10

1 Answers1

2

would imageStack (a class variable) be allocated on the heap or the stack?

If it is a static member variable, then it has static storage. If it is a non-static member variable, then it is a sub object of the class instance. It will be destroyed when the super object is destroyed.

However, according to the reference of VTK, the object pointed by the variable, and created by the function New, uses dynamic storage. It is not possible to create vtkObject instances (such as vtkImageData) on the stack.

is [the assignment] freeing the old memory it was pointing to prior?

Possibly; not necessarily.

If the smart pointer used to point to an object, it will no longer reference that object after it has been assigned a new value. The VTK reference is light on details, but it does say that the smart pointer uses reference counting. Presumably when the last reference is removed, the object is destroyed.

eerorika
  • 232,697
  • 12
  • 197
  • 326