[Bugs & Requests][Wiki]

5.2. Common Coding Questions

Q: What's the deal with this vRef stuff?
Q: What's the deal with meta_cast?

Q: What's the deal with this vRef stuff?

A: VOS uses a reference-counted memory management scheme. This means that each reference-counted object (implemented by subclassing "RefCounted" in the C++ library) has a "count" associated with it. This count is the number of times that this object is pointed ("referred") to somewhere in the running program. When a new reference is created (the refcounted object is "acquired") the reference count is incremented. When the a reference is destroyed (the refcounted object is "released") the count is decremented. When the reference count drops to zero, the object can be safely deallocated because we know there are no references to it left in the program.

The purpose of vRef is help you use with VOS's reference counting with a minimum amout of fuss. The vRef template is what is known as a "smart pointer". It is a small class which holds the reference to some object and automatically releases that reference when the vRef class is destroyed. It frees you from most of the hassle of dealing with memory management (at least as far as vobjects and related classes are concerned.) You should always use vRef whenever you get a RefCounted object from VOS.

vRef supports some implicit casting as well, as well as the dereference operator ->, allowing you to use it a bit like a regular pointer. See the API documentation for details, however.

Q: What's the deal with meta_cast?

A: Being polymorphic, Vobjects may implement many different interfaces. The mechanism to select between these interfaces is meta_cast(). This method is intended to appear similar to other C++ typecasting functions (dynamic_cast, reinterpert_cast, static_cast) so it should be comfortable if you are familiar with C++ casts. Using meta_cast is simple: you give it a Vobject and a desired interface class, and you get back a reference to of the appropriate class. If the Vobject does not support the desired class, then it will return NULL. It works well with vRef. An example:

try {
    vRef<Vobject> myobject = findObject("foo");
    vRef<FunkyInterface> theFunk = meta_cast<FunkyInterface>(myobject);
    if(theFunk.isValid()) {
    } else {
        LOG("myprogram", 2, "foo does not have a funky interface!");
} catch(Vobject::NoSuchObjectError&) {
    LOG("myprogram", 2, "foo does not exist");

This dynamic polymorphism is implemented using the MetaObject extensions discussed earlier. Each interface is usually a different actual C++ object. Behind the scenes these objects are rigged up to seamlessly act as the same logical Vobject. Internally, meta_cast works by going through each metaobject extension attached to the object and performing a C++ dynamic_cast to test for support for the desired interface; the first object which does support the interface is returned to the user.