jeudi 24 novembre 2016

C++ pointer spoofing

I am currently working on a piece of code in which lots of pointers are used without proper ownership control. In some cases, it becomes a huge contraint because everything has to be initialized properly and can't be changed afterwards. So far I have been using dummy wrappers

class MyObject
{
    int myMethod(int i){ return i; }
};
class MyObjectWrapper
{
     MyObject *obj = nullptr;
     int myMethod(int i){ if(obj) return obj.myMethod(i); }
     void setObject(MyObject *obj){ this->obj = obj; }
}

I am wondering if there is a way to do pointer "spoofing" by returning an object that is not actually a pointer but has the type of one, so that I can return a smart pointer instead of the regular pointer without changing the rest of the code. Is there a way of achieving that?

Additionnally, this led me to think about boost::optional. How is it implemented? Is boost using a lot of preprocessing for reflection? I cannot understand how it is possible to "intercept" a method call on a variable without neither knowing the name of the method nor using heavy preprocessing.

In case the answers are simple NOs, are you aware of any design pattern that can be used to work around my issues?

Aucun commentaire:

Enregistrer un commentaire