A const link is passed to the function, for example:

void someFun(const Objtype& object){} 

How to make the resulting object available to other functions without passing it every time. Those. I want to make it global, something like the following:

 Objtype globalobject; void someFun(Objtype& object){ globalobject = object; } void someFun1(){ globalobject.getSomeData(); } void someFun2(){ globalobject.getSomeData(); } 

How to do this if I get const Objtype &?

    2 answers 2

    There are two questions here. Do you need a copy or a link to the same object? Can I copy an object?

    Need a copy + you can copy:

     Object global; voif foo(const Object &object){ global = object; } 

    Need a copy + can not be copied:
    Here, alas, no way

    Need link:
    Links should not be left un-initialized or redirected. Therefore, instead of a link, you should take a pointer:

     const Object *global; voif foo(const Object &object){ global = &object; } 

    If you need to change the state of this object, you can do this:

     Object *global; voif foo(const Object &object){ global = const_cast<Object*>(&object); } 

    But this is a slippery slope. If you change an object that was originally passed as immutable, then you can get a subtle bug at the execution stage.

    • Modifying an object received by const_cast is not a bug, and UB is gbg
    • And if poshamanit? - Qwertiy
    • @gbg, if my memory serves me, then UB is the removal of constancy from constants. And removing constancy from links and pointers to objects that were not constants was originally a completely legitimate operation. - yrHeTaTeJlb
    • @yrHeTaTeJlb: But if the object is passed as const, with good chances, it is really const. - VladD
    • @VladD, nevertheless, the use of const_cast is not itself UB, but only in specific cases. - ixSci

    I hate global variables :) Therefore - this is an option:

     const ObjectType& single(const ObjectType * o = nullptr) { static const ObjectType *obj = nullptr; if (o) obj = o; return *obj; } void someFun(const ObjectType& object) { // ... single(&object); } 

    Next, to get - just call single() .

    But! it's all very dumb games. Imagine that in someFun we are passing a temporary object. Do not explain further? ...

    Or:

     int i = 5; someFun(i); i = 6; cout << single() << endl; 

    So const . In short, you can do almost everything. The question is why? Problems can outweigh the benefits very easily.