Consider this snippet:
#include <memory>
#include <iostream>
struct A
{
const int& getv()
{
return v;
}
int v{42};
};
struct Shared
{
Shared(std::shared_ptr<A> someA)
: intRef{someA->getv()}
{
}
const int& intRef;
};
Shared createShared()
{
auto sharedA = std::make_shared<A>();
return Shared(sharedA);
}
int main()
{
auto shared = createShared();
std::cout <<"Value of intRef " << shared.intRef;
return 0;
}
Why is there no segfault when accessing intRef
in std::cout <<"Value of intRef " << shared.intRef
?
Shared
takes a shared_ptr<A>
and stores a reference to the int
in A
.
The function createShared()
creates a shared_ptr<A>
and passes this to the constructor of Shared
.
When createShared()
returns, the shared_ptr<A>
gets deleted.
I would have thought that any subsequent access to intRef
of the object returned from createShared()
will segfault, since the heap no longer holds this object.
Is my reasoning correct and is it just a coincidence that the segfault does not happen right on the spot?
In general, can you guide me to a coding guideline rule of CppCoreGuidelines where one should not take references of contents which live behind a smart pointer?