Code:
#include <iostream>
using namespace std;
class Item
{
int num;
public:
Item(int i) : num(i) {};
int getNum() const { return num; }
};
class ItemPool
{
public:
Item* getItem (int);
};
Item* ItemPool::getItem (int n)
{
static Item myX(0);
if (n%2) return &myX;
else return new Item(n);
}
void main()
{
ItemPool coll;
for (int i=0; i<100; i++)
{
Item* anX = coll.getItem(i);
cout<<anX->getNum()<<’\n’;
}
}
Question:
1) Which semantic problem in execution does this program have?
2) Change only the main() function so that the behavior of the program remains the same, but that this problem is eliminated.
Thanks!!
The semantic problem is that the
ItemPool::getItem()method can return a pointer to either a dynamically allocated object, or a static one. It is not clear who takes ownership of the dynamically allocated object, and the caller has no way of knowing if they have to deallocate the object or not, without knowing the details of the implementation of theItemPool::getItem().I see no way of changing eliminating the problem and keeping the program behaviour the same. The program behaviour is erroneous, so fixing the problem would change its behaviour.
You can modify
main()to deallocateItemswheni%2==0after thecout. But that would change the behaviour of the program, in that there would no longer be a memory leak.