Tra*_*kel 5 c++ destructor initialization
如何抑制类型的自动初始化和销毁?虽然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;
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出是:
Created: 100
Destroyed: 100
Run Code Online (Sandbox Code Playgroud)
我希望它是:
Created: 0
Destroyed: 0
Run Code Online (Sandbox Code Playgroud)
我唯一的想法是制作m_buffer
一些简单的构造和破坏类型char
,然后依靠operator[]
为我包装指针数学,虽然这似乎是一个可怕的黑客解决方案.另一种解决方案是使用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;
}
Run Code Online (Sandbox Code Playgroud)
输出是正确的:
Created: 0
Destroyed: 0
Run Code Online (Sandbox Code Playgroud)
您可以将数组创建为数组char
,然后在需要时使用放置new
来创建元素。
template <typename T, size_t KCount>
class Array
{
private:
char m_buffer[KCount*sizeof(T)]; // TODO make sure it's aligned correctly
T operator[](int i) {
return reinterpret_cast<T&>(m_buffer[i*sizeof(T)]);
}
Run Code Online (Sandbox Code Playgroud)
重新阅读你的问题后,你似乎想要一个稀疏数组,有时它的名称是映射; o)(当然性能特征是不同的......)
template <typename T, size_t KCount>
class SparseArray {
std::map<size_t, T> m_map;
public:
T& operator[](size_t i) {
if (i > KCount)
throw "out of bounds";
return m_map[i];
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
642 次 |
最近记录: |