I have the following simple code example:
#include <iostream>
#include <utility>
#include <memory>
using namespace std;
class resource
{
public:
void print() { cout << "Class Still Alive" << endl; };
};
resource* create_resource()
{
std::unique_ptr<resource> r = std::make_unique<resource>();
return r.get();
}
void execute_resource(resource* r)
{
r->print();
}
int main()
{
resource* r = create_resource();
execute_resource(r);
return 0;
}
The unique ptr r created in create_resource goes out of scope at the end of the function. At least this is my understanding of scope.
So how is the actual resource wrapped by the unique pointer still reachable and does create a segmentation fault since its owning unique pointer should have gone out of scope and deleted this?
Compiling using: g++ test.cpp -std=c++14