Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we delete an object in Dart?

Tags:

dart

I want to basically delete an object I created. How do we delete an object?

I checked Object definition here, but couldn't figure out way to do it. Also I am curious whether we can define destructors or not.

UPDATE The question is getting good answers. But I want to draw your attention to a case in which I want to delete my objects or call destructor. Let's say we want to create a pace using that you can connect rectangles via the ports placed on it. So the idea is to have an object that has a reference to the body of the rectangle and the ports placed at two ends. In fact, that object might need some other properties like [bool] selected or [bool] dragging or [List<RectElement>] connectedSquares. For example, when user selects the rectangle and hits backspace, I want to make sure the rectangles are gone and my object is properly deleted. So this use case may give some more insight into the question.

like image 271
mert Avatar asked Dec 09 '13 22:12

mert


People also ask

How do you delete an object?

Right-click over the objects you want to delete, and choose Delete. In the Delete dialog box, select the objects you want to delete from the list.

How do you delete a class object?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


2 Answers

You don't need to actively delete objects in Dart.

Dart is a garbage-collected language, so any object that you don't hold any references to will eventually be garbage collected and freed by the runtime system.

So all you have to do is to clear any variables you have that reference the object.

Garbage collection is really implicit in the language specification. The specification doesn't say so that garbage collection exists (it doesn't even mention the concept), but the language and libraries are designed in such a way that garbage collection is possible: Objects that the program cannot find a reference to anywhere also can't affect the program's behavior any more, so it is undetectable that they are being collected and deleted by the garbage collector.

like image 175
lrn Avatar answered Oct 06 '22 00:10

lrn


Make sure that you don't hold a reference to the object so it can be GCed.

x = null;
like image 25
Günter Zöchbauer Avatar answered Oct 06 '22 01:10

Günter Zöchbauer