What will be the output of the following C++ code?
#include <new>
#include<cstdlib>
#include <iostream>
using namespace std;
class X;
struct Node
{
X* data;
bool filled;
Node() : filled(false) { }
};
class X
{
static Node buffer[];
public:
int number;
enum { size = 3};
void* operator new(size_t sz) throw (const char*)
{
void* p = malloc(sz);
if (sz == 0)
throw "Error: malloc() failed";
cout << "X :: operator new(size_t)" << endl;
return p;
}
void *operator new(size_t sz, int location) throw (const char*)
{
cout << "X :: operator new(size_t, " << location < ")" << endl;
void* p = 0;
if (location < 0 || location >= size || buffer[location].filled == true)
{
throw "Error: buffer location occupied";
}
else
{
p = malloc(sizeof(X));
if (p == 0)
throw "Error: Creating X object failed";
buffer[location].filled = true;
buffer[location].data = (X*) p;
}
return p;
}
static void printbuffer()
{
for (int i = 0; i < size; i++)
{
cout << buffer[i].data->number << endl;
}
}
};
Node X::buffer[size];
int main()
{
try
{
X* ptr1 = new X;
X* ptr2 = new(0) X;
X* ptr3 = new(1) X;
X* ptr4 = new(2) X;
ptr2->number = 10000;
ptr3->number = 10001;
ptr4->number = 10002;
X :: printbuffer();
X* ptr5 = new(0) X;
}
catch (const char* message)
{
cout << message << endl;
}
}
#include <new>
#include<cstdlib>
#include <iostream>
using namespace std;
class X;
struct Node
{
X* data;
bool filled;
Node() : filled(false) { }
};
class X
{
static Node buffer[];
public:
int number;
enum { size = 3};
void* operator new(size_t sz) throw (const char*)
{
void* p = malloc(sz);
if (sz == 0)
throw "Error: malloc() failed";
cout << "X :: operator new(size_t)" << endl;
return p;
}
void *operator new(size_t sz, int location) throw (const char*)
{
cout << "X :: operator new(size_t, " << location < ")" << endl;
void* p = 0;
if (location < 0 || location >= size || buffer[location].filled == true)
{
throw "Error: buffer location occupied";
}
else
{
p = malloc(sizeof(X));
if (p == 0)
throw "Error: Creating X object failed";
buffer[location].filled = true;
buffer[location].data = (X*) p;
}
return p;
}
static void printbuffer()
{
for (int i = 0; i < size; i++)
{
cout << buffer[i].data->number << endl;
}
}
};
Node X::buffer[size];
int main()
{
try
{
X* ptr1 = new X;
X* ptr2 = new(0) X;
X* ptr3 = new(1) X;
X* ptr4 = new(2) X;
ptr2->number = 10000;
ptr3->number = 10001;
ptr4->number = 10002;
X :: printbuffer();
X* ptr5 = new(0) X;
}
catch (const char* message)
{
cout << message << endl;
}
}
A. X::operator new(size_t)
B. Error
C. Runtime error
D. operator new(size_d)
Answer: Option C
Join The Discussion