简体   繁体   中英

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:

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. When it pops out of the cdll constructor, it "forgets" everything it's done. The address of this in the cdll constructor matches the address of y . I've also tried Queue<datatype>::Queue() : Queue::CDLL<datatype>() {} but the same behavior persists.

I've taken a look at:

C++ Inheritance constructor override , What are the rules for calling the superclass constructor? 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.

This:

Queue<int> * y = &Queue<int>(2, 1);

Is not valid C++. It is apparently accepted by an MSVC extension. 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.

To disable MSVC extensions, use the /Za compiler switch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM