Cannot get display node of customized markups in c++

I customized a node called vtkMRMLDeformableROINode which is derived from vtkMRMLMarkupsNode.
I tried to get its display node and set some properties.

The code below written in python works fine without any problem:

roiNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLDeformableROINode")
# setup Node ...
displayNode = roiNode.GetDisplayNode()
displayNode.SetDisplayableOnlyInView("vtkMRMLSliceNodeRed")

However, when I trying to do the same thing in C++:

auto displayNode = vtkMRMLMarkupsDisplayNode::SafeDownCast(roiNode->GetDisplayNode());
displayNode->SetDisplayableOnlyInView("vtkMRMLSliceNodeRed");

Segmentation fault occured and by printing out the backtrace I found out that roiNode->GetDisplayNode() returned a nullptr.

Why does the C++ code performed different with python code? How can I fix it?

I figured out the reason.

In c++ version, I called qSlicerApplication::application()->mrmlScene()->StartState(vtkMRMLScene::BatchProcessState) before adding the new node. If I comment out this line, everything works just fine.

So can anyone gives an advice about how or when should I use the State feature?

After you create a new displayable node programmatically it is your responsibility to add display node as well. The easiest way for creating the display node and associate it with the markup node is to call CreateDefaultDisplayNodes() method.

Use it if you manipulate at least 10-20 nodes. Starting/ending batch processing state is quite costly (rebuilds scene models in all node selector GUI widgets, etc.), so it is only worth activating it if you save a lot of time by not ignoring scene updates during the batch process state.