【发布时间】:2017-10-17 06:39:22
【问题描述】:
所以我的意图是构建一个“Multibuffer”,它具有可定义数量的“SingleBuffers”。存储的类型是免费的,因此我想使用模板。我只是玩了一下。
但是我不知道如何在Multibuffer的Constructor中直接初始化Singlebuffers。 我不会写下完整的类,而是写下构造函数来显示问题。在使用模板类时,我在标题中定义了这两个类。
所以我的 Singlebuffer-Constructor 看起来像这样:
enum BufferState_E
{
BUFFER_WRITE = 0,
BUFFER_READ,
BUFFER_FORCED_READ // buffer is forced for reading
};
template<typename T>
class SingleBuffer
{
public:
/*
* Constructor
* constructs a Buffer with the concrete data field
*/
SingleBuffer( unsigned int buffer_size )
: entry_ptr_ ( new T[buffer_size]() ) //default constructor works?
, end_entry_ptr_ ( &entry_ptr_[buffer_size-1] )
{
read_entry_ptr_ = &entry_ptr_[0];
write_entry_ptr_ = &entry_ptr_[0];
state_ = BUFFER_WRITE;
}
private:
/* The pointer to the buffer */
T * entry_ptr_;
/* the pointers to the entry which is currently read/written */
T *read_entry_ptr_;
T *write_entry_ptr_;
/* the pointer to the end of the buffer */
T * end_entry_ptr_;
/* The state of the buffer */
BufferState_E state_;
}
还有我的 Multibuffer-Constructor,它实例化了大量的 Singlebuffers(我在有问题的代码行之后写了一条注释):
template<typename T>
class MultiBuffer : public BufferBase
{
public:
MultiBuffer( unsigned int buffer_size = 2000 // size of one buffer
, unsigned char number_of_buffers = 5 // how many buffers are there?
, const char* name = "MultiBuffer"
)
: buffer_ptr_ ( new SingleBuffer<T>[number_of_buffers](buffer_size) ) // the problem line!
, end_buffer_ptr_ ( &buffer_ptr_[number_of_buffers-1])
, buffer_size_ ( buffer_size )
, number_of_buffers_ ( number_of_buffers )
{
read_buffer_ptr_ = &buffer_ptr_[0];
write_buffer_ptr_ = &buffer_ptr_[0];
}
private:
/* the normal buffer-pointer */
SingleBuffer<T> *buffer_ptr_;
/* the pointer to the end of the buffers */
SingleBuffer<T> *end_buffer_ptr_;
/* the pointer to the current read-buffer */
SingleBuffer<T> *read_buffer_ptr_;
/* the pointer to the current write-buffer */
SingleBuffer<T> *write_buffer_ptr_;
/* the buffer-size */
unsigned int buffer_size_;
/* the number of buffers */
unsigned char number_of_buffers_;
}
所以我的编译器总是在标记的代码行中告诉我:“ISO C++ 禁止在新数组中初始化”。查找“新”的 cpp-reference 并没有真正的帮助,其他与模板有关的问题也没有帮助。 如果我只使用默认构造函数,就像您在 Singlebuffer 初始化中看到的那样,它似乎可以工作,但是只要我想将一个值传递给我自己定义的模板类的构造函数,它就会崩溃。我确实设法在没有直接在 Multibuffer-Constructor 中初始化但使用循环迭代“缓冲区数量”并在每次迭代中分配内存时强制它构建,但这不是它应该如何工作,除了我真的不是知道这是否真的没有错误。
而且我不想使用 std::-functions,因为我正在开发嵌入式系统。编译器是 GCC 4.8.1,也不能更改,也不支持 lambda 表达式...
我希望有可能。到目前为止,谢谢。
【问题讨论】:
-
请考虑minimal reproducible example的最小和完整方面。
-
一个支持
new的嵌入式系统应该支持std::vector就好了。 -
好的,我删除了一个不必要的继承并添加了 BufferState_E-enum。我希望现在可以了。它完全编译为我的错误。
标签: c++ arrays templates constructor new-operator