如何抑制类型的自动初始化和销毁?虽然T buffer[100]
自动初始化了buffer
的所有元素,并在它们超出作用域时销毁它们,但这并不是我想要的行为。
#include <iostream>
static int created = 0,
destroyed = 0;
struct S
{
S()
{
++created;
}
~S()
{
++destroyed;
}
};
template <typename T, size_t KCount>
class fixed_vector
{
private:
T m_buffer[KCount];
public:
fixed_vector()
{
// some way to suppress the automatic initialization of m_buffer
}
~fixed_vector()
{
// some way to suppress the automatic destruction of m_buffer
}
};
int main()
{
{
fixed_vector<S, 100> arr;
}
std::cout << "Created:\t" << created << std::endl;
std::cout << "Destroyed:\t" << destroyed << std::endl;
return 0;
}
这个程序的输出是:
Created: 100
Destroyed: 100
我希望您能将其变为以下内容:
我希望它是:
Created: 0
Destroyed: 0
我的唯一想法是将 m_buffer
设计成一种像 char
这样的可以轻松构造和析构的类型,然后依赖于 operator[]
来为我封装指针运算,虽然这似乎是一个可怕的 hack 解决方案。另一个解决方案是使用 malloc
和 free
,但这会给我带来不必要的间接性。
我之所以想这样做,是因为我正在制作一个容器,我不想为我不使用的东西支付初始化开销。例如,如果我的 main
函数是:
int main()
{
{
std::vector<S> vec;
vec.reserve(50);
}
std::cout << "Created:\t" << created << std::endl;
std::cout << "Destroyed:\t" << destroyed << std::endl;
return 0;
}
输出将是正确的:
Created: 0
Destroyed: 0