ter*_*kuh 4 c++ arrays pointers
我以为我做了一些蠢事 - 至少我认为是这样.我的问题是:为什么这有效?
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;
}
Run Code Online (Sandbox Code Playgroud)
该代码在C++ 14(Visual Studio)中完美运行.不应该在第二次之后抛出异常push_back吗?
更新问题:
如果您没有pContainer使用new 进行初始化,那么该怎么办pContainer = &T()?这不会以某种方式影响记忆甚至危及其他程序吗?当我使用在构造/破坏时打印出来的类时,所有创建的对象将在构造后立即销毁.为什么即使在破坏后我也可以使用它们?