about smartpoint

#include<vtkObjectFactory.h>
#include <iostream>
#include<vtkObject.h>
#include<vtkImageData.h>
#include<vtkImageActor.h>
#include<vtkSmartPointer.h>
class MyClassA :public vtkObject
{
public:
	vtkTypeMacro(MyClassA, vtkObject);
	static MyClassA* New();

	void Setactor(vtkSmartPointer<vtkImageActor> acto);
protected:
	MyClassA();
	~MyClassA() override;
private:
	vtkSmartPointer<vtkImageActor> actor1;
	//vtkSmartPointer<vtkImageActor> actor2;
	vtkSmartPointer<vtkImageData> image;
	MyClassA(const MyClassA&) = delete;
	void operator=(const MyClassA&) = delete;
};

vtkStandardNewMacro(MyClassA);
MyClassA::MyClassA()
{
	actor1 = nullptr;
	image = vtkSmartPointer<vtkImageData>::New();
	//actor2=vtkSmartPointer<vtkImageActor> ::New();
	cout << "MyClassA构造" << endl;
}

MyClassA::~MyClassA()
{
	cout << "MyClassA析构" << endl;
}
void MyClassA::Setactor(vtkSmartPointer<vtkImageActor> acto) {

	//
	actor1 = acto;
	//actor2->Print(cout << actor2);
}
class MyClassB :public vtkObject
{
public:
	vtkTypeMacro(MyClassB, vtkObject);
	static MyClassB* New();
	vtkSmartPointer<MyClassA> CreateMyClass();
	MyClassA* classAA;
	//vtkSmartPointer<MyClassA> classAA;
	vtkSmartPointer<vtkImageActor> actor;
protected:
	MyClassB();
	~MyClassB() override;
private:


	
	MyClassB(const MyClassB&) = delete;
	void operator=(const MyClassB&) = delete;

};

vtkStandardNewMacro(MyClassB);
MyClassB::MyClassB()
{
	cout << "MyClassB构造" << endl;
	classAA = vtkSmartPointer<MyClassA>::New();
	actor= vtkSmartPointer<vtkImageActor>::New();
}

MyClassB::~MyClassB()
{
	cout << "MyClassB析构" << endl;
}

int main()
{

	auto B = vtkSmartPointer<MyClassB>::New();
	
	B->classAA ->Setactor(B->actor);
	cout << "成功返回"<<endl;
	
}

Here is a code, including a bug. The reason for the bug is that MyClassA is a common pointer, and smart pointer is used during instantiation. This code has randomness and can run normally occasionally. I want to know why randomness occurs?

As you said, the source of the bug is this:

MyClassA* classAA = vtkSmartPointer<MyClassA>::New();

A vtkObject is deleted when there are no references to the object.
A smart pointer holds one reference to the object.

In this code, a smart pointer is created, the common pointer is stored in classAA, and then the smart pointer is destroyed (since the smart pointer itself isn’t stored anywhere). So classAA is a dangling pointer, meaning, it points to an object that has been deleted.

When objects are deleted, they usually sit around unchanged for a while, until the computer uses the object’s memory space for something else. Sometimes the computer will leave that memory alone until your program finishes running, which allows your program to run normally. That’s why it only crashes sometimes, and not all the time.

1 Like

I see. Thank you very much.