ASL
Loading...
Searching...
No Matches
Reference-counted objects

Several classes implement reference counting so that objects are copied by reference (shared).

The object will be destroyed and freed when it no longer has references. For a separate copy of the object, there is a clone() method.

All containers such as Array, Map, Dic, Stack, HashMap, are shared this way. String is currently not shared but might be in the future.

Other shared classes also support inheritance and polymorphism: Xml, XmlText, Socket, TlsSocket.

It works like this. Suppose we have a shared class Shape and derived classes Circle and Square.

Shape shape1 = Circle(r); // a Circle is created in the heap and stored in shape1
a = shape1.area(); // gives PI * r^^2
Shape shape2 = shape1; // shape2 and shape1 are the same object in memory
Shape shape3 = shape1.clone(); // shape3 is a separate copy of shape1
Square shape4(l); // a Square is created with length l
a = shape4.area(); // gives l^^2

We can keep them in an array:

Array<Shape> shapes = {shape1, shape2, shape3, shape4};

We can check if an object is actually of a derived class, and cast it dynamically:

if(shape1.is<Circle>()) // returns true because now shape1 contains a Circle
{
shape1.as<Circle>().setRadius(10.0); // I can call a method that is only in Circle
}

For a non-owning pointer to the underlying object (e.g. to avoid circular references in a graph), these classes have a ptr() method that returns a C::Ptr class object.

Shape::Ptr link = shape1.ptr();

We can check if two objects are the same (they point to the same memory):

if(shape1.is(shape2)) // true

Objects of these types are automatically constructed (initialized), as is usual in C++, and directly usable. If for some reason you need to create a non-initialized object and defer construction you can create the object with a null pointer argument.

Shape shape((Shape::Ptr)0); // or Shape shape(nullptr); in C++11
shape = isCircleRequired ? Circle() : Square();