How to copy constructor with unique_ptr in Linked Stack

So, moving from Linked List, I now have to build a Linked Stack, which I think is pretty much similar to it. However, I get an access error, saying that cannot access to private member which I do not understand, since I was not trying to access any private members at all....

LinkedNode.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <memory>
using namespace std;

template <class T>
class LinkedNode 
{

    public:

        LinkedNode(T newElement, unique_ptr<LinkedNode<T>> newNext)
        {
            element = newElement;
            next = newNext;
        }

        T GetElement() {return element;}

        void SetElement(T x) {element = x;}

        unique_ptr<LinkedNode<T>> newNext() {return next;}

        void SetNext(unique_ptr<LinkedNode<T>> newNext) {next = newNext;}

    private:
        T element;
        unique_ptr<LinkedNode<T>> next;
};


CompactStack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once
#include"LinkedNode.h"

using namespace std;

template <class T>
class CompactStack 
{

    public:

        CompactStack() {}
        bool IsEmpty() const { return head == 0; }

        T Peek() 
        {
            assert(!IsEmpty());
            return head-> GetElement();
        }

        void Push(T x) 
        {
            unique_ptr<LinkedNode<T>> newhead(new LinkedNode<T>(x, head));
            head.swap(newhead);
        }

        void Pop() 
        {
            assert(!IsEmpty());
            unique_ptr<LinkedNode<T>> oldhead = head;
            head = head->next();
        }

        void Clear() 
        {
            while (!IsEmpty())
            Pop();
        }

    private:
        unique_ptr<LinkedNode<T>> head;
};


And this is the error that I've got

Error 1 error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' e:\fall 2013\cpsc 131\hw4\hw4\hw4\compactstack.h 22

Last edited on
unique_ptr cannot be copied, this is by design.
Is there a workaround way to do that ? I mean, for my program to run ?
Use a constructor initializer list ;)
Last edited on
I don't know how. Can you show me ?
Instead of this:
11
12
13
14
15
        LinkedNode(T newElement, unique_ptr<LinkedNode<T>> newNext)
        {
            element = newElement;
            next = newNext;
        }
Try this:
11
12
13
14
15
        LinkedNode(T newElement, unique_ptr<LinkedNode<T>> newNext)
        : element(newElement)
        , next(newNext)
        {
        }
Topic archived. No new replies allowed.