Note: I got this question from a friend of mine. It was given to him in an interview exam. I'd done programming in C++ in my early days of university. Even though the question looked easy on the first glance, I couldn't find a good answer to it. That's why I'm asking here.
Given this C++ code below, please answer to the following 3 questions:
template<typename T>
class Array
{
public:
Array(unsigned arraySize):
data(0), size(arraySize)
{
if(size > 0)
data = new T[size];
}
~Array()
{
if(data) delete[] data;
}
void setValue(unsigned index, const T& value)
{
if(index < size)
data[index] = value;
}
T getValue(unsigned index) const
{
if(index < size)
return data[index];
else
return T();
}
private:
T* data;
unsigned size;
};
RAII
[See Here}Ways to fix this problem
std::vector
nullptr
std::size
or size_t
size
which might conflict with std::size
when using namespace std
is used.if(data) delete[] data;
with delete[] data;
when nullptr
is used to initialized the values.std::out_of_range
in getValue
and setValue
Answered by: Bethsheba, Slava, Jesper Juhl, Vlad from Moscow , eerorika