Before explaining the question i want to mark that i know that given example is bad code. I am already looking at std::shared_ptr
to achieve my goal in more reasonable way. Reason for this post is just my curiosity and desire to learn new stuff. Thank You in advance for help!
I was today a little messing with my parser code. Optimalization stuff etc. I focused on few instances of object that where unnecesarly cloned all the way throught parsing. I had not-so-deliberate idea to create few global instances and access them by static method. Anyway (strongly simplifing) i ended with this somewhat interesting case:
class class_a
{
class_a();
class_a& referenceToObject;
};
class_a& getGlobalObject();
class_a::class_a()
:referenceToObject(getGlobalObject())
{}
class_a object;
class_a object2;
class_a& getGlobalObject()
{
return object2;
}
This obviously means that i did quite a few things very wrong, but at this branch, optimization is the most important matter.
I am interested what would happen in code like this in wider collection of compilers. GetGlobalObject()
is returning reference to object that hadn't it's constructor called. Still it's returning only the reference - that is pointer to space on memory (somewhere on data segment or heap, dunno) known at compile time.
Assuming that nothing will call any method nor any member of object2
reference, is this example undefined behavior?