This repository contains a simple example of handling resources in C++.
The supplied memory_resource.hpp file provides the following functions:
-
MemoryResource acquire_resource(int size);
Returns a
MemoryResourceobject consisting of an array ofsizeints -
void release_resource(MemoryResource& resource);
Destroys a
MemoryResourcepreviously acquired byacquire_resource() -
int access_resource(const MemoryResource& resource, int index);
Returns the value at position
indexin theMemoryResourcearray
(Many C libraries provide APIs like this.)
The starter code in main.cpp uses the above functions to calculate the
sum of the values in a MemoryResource of a given size; however, if the
total is too small (less than 100), it returns zero instead.
Unfortunately, the use_resource_example() function in main.cpp has a bug!
Can you spot what it is?
This bug can be avoided by properly using RAII
-
Write a new class
ResourceHandlewhich manages aMemoryResourceby automatically callingacquire_resource()when it is created, andrelease_resource()when it is destroyed -
Add a member function to
ResourceHandlewhich allows you to access the resource usingaccess_resource() -
Use this class to fix the bug in
use_resource_example()
What happens when you create a copy of a ResourceHandle object? Why?
- Update your
ResourceHandleclass to use the suppled functioncopy_resource()as appropriate to solve this problem