Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为没有默认构造函数的类型初始化静态大小的数组_C++_Arrays_Templates_Constructor_Default Constructor - Fatal编程技术网

C++ 为没有默认构造函数的类型初始化静态大小的数组

C++ 为没有默认构造函数的类型初始化静态大小的数组,c++,arrays,templates,constructor,default-constructor,C++,Arrays,Templates,Constructor,Default Constructor,我正在编写一个简单的模板循环缓冲区: template <typename T, size_t N> class CircularBuffer { T _buf[N]; T *_data; size_t _head; size_t _count; size_t _capacity; CircularBuffer(): _data(nullptr), _head(0),

我正在编写一个简单的模板循环缓冲区:

template <typename T, size_t N>
class CircularBuffer {

    T      _buf[N];
    T     *_data;
    size_t _head;
    size_t _count;
    size_t _capacity;

    CircularBuffer():
            _data(nullptr),
            _head(0),
            _count(0),
            _capacity(N) {}

protected:

    T* buffer() {
        if (_count <= N) return &_buf;
        else return _data;
    }

public:

    T& operator[](size_t i) {
        size_t j = i % _count;
        j = (_head + j) % _capacity;
        return buffer()[j];
    }

    T& push_back(const T& o) {
        if (_count == _capacity) {
            dynamically_allocate_data();
        }
        size_t j = (_head + _count++) % _capcity;
        buffer()[j] = o;
    }

    T pop_front() {
        size_t old_head = _head;
        _head = (_head + 1) % _capacity;
        return buffer()[old_head];
    }

};
模板
类循环缓冲{
T_buf[N];
T*_数据;
头的大小;
大小和数量;
容量大小;
循环缓冲()
_数据(空PTR),
_总目(0),,
_计数(0),
_容量(N){}
受保护的:
T*缓冲区(){

如果(_count使用
std::optional
(或者
boost::optional
,如果编译器是17之前的版本),您可以将静态数组定义为
std::optional;


std::optional
类型支持布局构造(因此
T
不需要默认构造函数)并静态分配,这样可以满足您的要求,不是吗?

placement new
不分配内存。您可能可以在这个角色中使用。@appleapple我如何声明一个静态数组
void*
?您可以使用
(未签名)char[]
您想要的
std::aligned_storage
和placement new。