Why does it work? [C ++; pointer void]

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]; //initialize as array with size 1
        unCount = 0U; //counter
    }
    ~yarray() {
        delete[] pContainer; //cleanup
        pContainer = nullptr;
    }

    void push_back(T data)
    {
        ((T*)pContainer)[unCount] = data; //set (shouldn't it throw an exception when unCount > 0?
        unCount++; //increment
    }

    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?

+4
source share
2

undefined. .

, , .

+7

. 4 k (4096 ). 4k , .

  • xxxxxxxxxxxxDDDDD (x D).
  • - .

, .

, valgrind (linux) (windows), , , .

( arduino), , . , , - , .

+1

Source: https://habr.com/ru/post/1620941/


All Articles