Charlie Charlie - 1 month ago 18
C++ Question

Does this object exist? c++ scope/inheritance

I've been playing around with a way to handle function-objects and I'm curious about if I'm misunderstanding something, possibly creating a problem further down the line. I ask, because I want to see this approach work, and understand better what I'm doing.

The idea is quite simple: I create a virtual access pointer like this:

struct access { virtual void tick() = 0; };


The obj (out of many different) the access pointer will work on:

struct obj1 :public access
{ void tick() { cout << "I'm being called " << endl; } };


And I have the "controller" class that will (eventually) hold and control the flow of the actions:

class container
{
vector<access*>acc_objects; //do these exists by themselves?

public:
void obj_add(access &x) { acc_objects.push_back(&x); }
void tick() { for (auto x : acc_objects)x->tick(); } //active functors

}controller; //there will be only 1


The goal (eventually) will be to send a pointer to various objects, to a vector of access pointers, thereby being able to call them as if they were the same. Either way, whats confusing me at this point is when I do this:

{ //in scope
obj1 anobj;
conts.obj_add(anobj);

int x=1; //x in scope
}

conts.tick(); //referrign to the object still works
cout<<x<<endl; //but this does not


Why can I still refer to obj1? Is this just undefined behaviour, or does the object exist by reference only somehow. Im also asking, because finding a way to have functor-objects exist and vanish reliably is something I'm trying to accomplish.

Edit: cleaned up the question, it was not about object splicing at all as it turned out.

Answer

Your bug is not object slicing per se.

{
    obj1 anobj;

    // ...
}

Here, anobj goes out of scope, and gets destroyed at the end of the scope.

Meanwhile, inside the scope, a pointer to anobj gets saved in your container. Referencing the object via the pointer, after the scope has ended results in a reference to a destroyed object.

Nothing was sliced anywhere. The entire object was destroyed, and the subsequent reference to the object comprises undefined behavior.