I thought I did something stupid - at least I thought it was. My question is: why does this work?
template<typename T>
class yarray
{
public:
yarray() {
pContainer = new T[1];
unCount = 0U;
}
~yarray() {
delete[] pContainer;
pContainer = nullptr;
}
void push_back(T data)
{
((T*)pContainer)[unCount] = data;
unCount++;
}
T operator[](const unsigned int & index)
{
if (index <= unCount)
return ((T*)pContainer)[index];
return T();
}
private:
void * pContainer;
unsigned int unCount;
};
int main()
{
yarray<int> klo;
klo.push_back(342);
klo.push_back(5563);
for (auto i = 0; i < 2; ++i)
std::cout << klo[i] << std::endl;
}
The code works fine in C ++ 14 (Visual Studio). Shouldn't an exception be thrown after the second push_back?
Refresh question:
What if you do not initialize with a pContainernew one, but with pContainer = &T()instead? Doesn't that affect memory or even threaten other programs? When I use a class that prints when it was created / destroyed, all objects that were created will be destroyed immediately after construction. Why can I use them even after destruction?
source
share