Search code examples
c++vtk

Why doesn't the changes on a shallow copy of a vtk object in C++ affect the original object


I have the following c++ code:

vtkNew _surf;
_surf->ShallowCopy(surf);
vtkIdType cellId = Get_ClosestCellId(_surf, seedxyz);
_surf->DeleteCell(cellId);
_surf->RemoveDeletedCells();

After creating _surf, we specify it as a ShallowCopy of surf then remove the cell closest to the seedxyz by calling _surf->DeleteCell

I thought that if I ShallowCopy like this, since _surf and surf share the same pointer, the modifications made to _surf would also be reflected in surf.

However, if you output the two in vtp format, _surf is modified but surf does not show the changes. Why is this?


Solution

  • I've made this very simple example.

    #include <stdio.h>
    
    class A{
    public:
        float* pos;
        void ShallowCopy(A* other){
            other->pos = pos;
        }
    
    };
    
    int main(int argc, char** args){
        A* surf = new A();
        float* pos = new float[1];
        pos[0] = 5;
        surf->pos = pos;
        A* b = new A();
        surf->ShallowCopy(b);
    
        printf(" startt: %f\n", surf->pos[0]);
    
        b->pos[0] = 10;
    
        printf(" first: %f\n", surf->pos[0]);
    
        float* other = new float[1];
        other[0] = 20;
        b->pos = other;
        printf(" after: %f\n", surf->pos[0]);
        delete surf, b;
        delete[] other, pos;
    }
    

    The output is:

    startt: 5.000000
    first: 10.000000
    after: 10.000000

    The idea is that the shallow copy uses the the same backing data, pos, so changes in pos are reflected in both copies. Both objects have their own pointer to pos so when you b->pos = other it isn't reflected in surf

    Since the object surf is a vtkPolyData we can hunt down the ShallowCopy docs vtkObject ShallowCopy.

    The goal of the method is to copy the data up to the array pointers only.

    Both vtkObjects have a list of CellId's, adding or removing cell id's will not be reflected in the other class. Changing the cells themselves would be reflected.