我是c +的新手,并试图准确理解我的代码发生了什么。
这些类都在它们自己的头文件中定义。代码如下。
队列:
template<class T> class Queue
{
public:
Queue(unsigned int size)
{
_buffer = new T[size]; //need to make sure size is a power of 2
_write = 0;
_read = 0;
_capacity = size;
}
/* other members ... */
private:
unsigned int _capacity;
unsigned int _read;
unsigned int _write;
T *_buffer;
};
序列号:
template<class T> class Queue;
template<class T> class Serial
{
public:
Serial(unsigned int buffer_size)
{
_queue = Queue<T>(buffer_size); //<---here is the problem
}
private:
Queue<T> _queue;
};
当我尝试像这样创建一个Serial实例时:
Serial<unsigned char> s = Serial<unsigned char>(123);
编译器抱怨没有没有参数的Queue构造函数,至少我认为这些错误意味着:
In instantiation of 'Serial<T>::Serial(unsigned int) [with T = unsigned char]': no matching function for call to 'Queue<unsigned char>::Queue()' ambiguous overload for 'operator=' in '((Serial<unsigned char>*)this)->Serial<unsigned char>::_queue = (operator new(16u), (((Queue<unsigned char>*)<anonymous>)->Queue<T>::Queue<unsigned char>(buffer_size), ((Queue<unsigned char>*)<anonymous>)))' (operand types are 'Queue<unsigned char>' and 'Queue<unsigned char>*') invalid user-defined conversion from 'Queue<unsigned char>*' to 'const Queue<unsigned char>&' [-fpermissive] invalid user-defined conversion from 'Queue<unsigned char>*' to 'Queue<unsigned char>&&' [-fpermissive] conversion to non-const reference type 'class Queue<unsigned char>&&' from rvalue of type 'Queue<unsigned char>' [-fpermissive]
当我向Queue添加一个空构造函数时,它编译没有任何问题。当我逐步使用调试器时,我看到它进入带有参数的构造函数,而不是空的。
为什么会这样?
答案 0 :(得分:5)
Serial(unsigned int buffer_size)
缺少member init list,因此必须首先使用默认构造函数创建_queue
,然后为其分配值(Queue<T>(buffer_size)
)。
此:
Serial(unsigned int buffer_size) : _queue(buffer_size) {}
将使用Queue(unsigned int)
构造函数,并且在没有默认构造函数的情况下工作。
答案 1 :(得分:1)
在查看OPs类并查看指针数组以及在CTOR中使用new时,我会以类似于此的方式设计类:
<强>队列强>
#ifndef QUEUE_H
#define QUEUE_H
template<class T>
class Queue {
private:
size_t size_;
size_t capacity_;
size_t read_;
size_t write_;
// Either of these depending on case of use or ownership
std::vector<std::shared_ptr<T>> buffer_;
std::vector<std::unique_ptr<T>> buffer_;
public:
Queue() {}
explicit Queue( size_t size ) : size_(size) {
buffer_.resize( size_ );
}
}; // Queue
#endif // !QUEUE_H
<强>串行强>
#ifndef SERIAL_H
#define SERIAL_H
template<class T> class Queue;
template<class T>
class Serial {
private:
Queue<T> queue_;
public:
Serial() {}
explicit Serial( size_t bufferSize ) {
queue_ = Queue<T>( bufferSize );
}
}; // Serial
#endif // !SERIAL_H
Serial Class不是什么大问题,因为它使用的是Queue类型的堆栈对象。现在对于Queue对象,因为它使用带有new operator
的指针,所以还必须有匹配的delete operator
,这直接表明析构函数必须管理某种内存资源。 。
正因为如此,我选择使用vector<smart_ptr>
代替array[size] raw pointers
。这有助于防止内存泄漏,悬挂指针等。至少写出这3个来完成Rule of 3
:
Destructor
Copy Constructor
Assignment Operator
可能需要编写这些来完成Rule of 5
:
Move Constructor
Move Assignment Operator