[英]C++ Class Template Constructor inheritance with pointers
I currently have the following Circularly Doubly Linked List as the parent (provided by the professor of my class): 我目前有以下循环双链表作为家长(由班级教授提供):
template <class datatype>
class CDLL
{
public:
struct node;
class iterator;
// Constructors
CDLL(void);
CDLL(unsigned int n_elements, datatype datum);
CDLL(const CDLL& rlist);
CDLL(iterator begin, iterator end);
// .. code ...
};
Our instructions were to create a Queue that inherits from this CDLL: 我们的指令是创建一个从此CDLL继承的队列:
template <class datatype>
class Queue : protected CDLL<datatype> {
public:
using CDLL<datatype>::CDLL;
// ... code ...
};
In my tests I have: 在我的测试中,我有:
Queue<int> x = Queue<int>(2, 1); // Creates a queue of: [1, 1]
Queue<int> * y = &Queue<int>(2, 1); // Creates a queue of: []
I have debugged this thoroughly and it walks through the constructor steps (pushing each element to the queue/cdll) and it walks through every step. 我已经对其进行了彻底的调试,它遍历了构造函数步骤(将每个元素推入队列/ cdll),并且遍历了每一步。 When it pops out of the cdll
constructor, it "forgets" everything it's done. 当它弹出cdll
构造函数时,它“忘记”了它所做的一切。 The address of this
in the cdll
constructor matches the address of y
. this
在cdll
构造函数中的地址与y
的地址匹配。 I've also tried Queue<datatype>::Queue() : Queue::CDLL<datatype>() {}
but the same behavior persists. 我还尝试了Queue<datatype>::Queue() : Queue::CDLL<datatype>() {}
但相同的行为仍然存在。
I've taken a look at: 我看了看:
C++ Inheritance constructor override , What are the rules for calling the superclass constructor? C ++继承构造函数重写 , 调用超类构造函数的规则是什么? and a few other questions with titles similar to this one but I can't seem to explain the behavior of this. 以及其他一些标题与此类似的问题,但我似乎无法解释其行为。
I have surfed google/SO and have tried many of the solutions many have suggested but to no avail. 我浏览过google / SO,并尝试了许多建议的许多解决方案,但无济于事。
This: 这个:
Queue<int> * y = &Queue<int>(2, 1);
Is not valid C++. 无效的C ++。 It is apparently accepted by an MSVC extension. 它显然已被MSVC扩展接受。 The issue is that, while this extension allows you to take the address of the temporary, it does not extend its lifetime; 问题是,尽管此扩展名允许您使用临时地址,但不会延长其寿命。 which means that this instance of Queue<int>
is destructed as soon as the initialization of y
is completed, leaving y
dangling and its further inspection via the debugger nonsensical. 这意味着,一旦y
的初始化完成,就会破坏Queue<int>
该实例,从而使y
悬空并通过调试器进行进一步检查是毫无意义的。
To disable MSVC extensions, use the /Za
compiler switch . 要禁用MSVC扩展,请使用/Za
编译器开关 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.