The member method constness in Entity Component System

You have an entity, it has many components, each component is allocated from its own pool, the entitiy holds a handle or an index, or whatever data sturcture (e.g. Map) used to get/query a component by type.

 

Then perhaps you want to add a getter to get a particular component in the Entity class. Apparently, this getter isn't changing any member variables of the Entity class, so you marked the method const. Often, you want 2 versions of this returned object, const and non-const, so you added the "NonConst" postfix to make it more clear for the API users. It will look more or less something like this:

AnimationComponent* Entity::GetAnimationComponentNonConst() const
{
    return GetComponentReadWrite<AnimationComponent>();
}

const AnimationComponent* Entity::GetAnimationComponent() const
{
    return GetComponentRead<AnimationComponent>();
}

 

This is 100% grammatically correct in C++. But isn't this awkward if not confusing?

First of all, const is only something you present to the compiler, it does not change any underlying data. Language like C# doesn't even have the concept of const. 

The reason people invented the const for a memember method, is to enforce people to care about the constness in their callstack, a const method cannot call non-const member metehods, the compiler won't let you.

Well, for an Entity Component System, the composition of an Entity is *Logical*, the underlying data layout or order is physically irrelavent. The association between an Entity and its components will stay const for the most of the time, untill you add or remove a component.

That said, methods that change the value of a comonent through the Entiy APIs are always const, if you are not caching anything on the Entity. But constness is "logical" right? It only resides in your human code to help you, after compilation, it will all be transformed into optimized code or nothing changes at all.

 

This is the case when Object Oriented Programming concept invented in C++ appeared to be useless if not ambiguous in Data Oriented paradigm. Actually, there is ambiguity in C, a const pointer that doesn't change, doesn't mean the address it points to cannot get mutated. Const pointer to const memory is one of the most confusing parts in learning C/C++ programming.

 

So what do we do? In my oppinion, the const-correctness falls on to the shoulder of the programmers'. If you are an API designer, mark the APIs "Logically", which means dropping the const for a method that is supposed to change things in association with the class you are working on. If you are an API user, think whether you should use the const or nonconst version when you write your code - not until the compiler complains.

 

https://isocpp.org/wiki/faq/const-correctness#overview-const

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章