Accessing the structure field in unique_ptr causes access violation

Viewed 200

I have a class like this:

template <typename T>
class Store {

private:
    struct pointNode {
        T data;
        std::unique_ptr<pointNode> next;
    };
    std::unique_ptr<pointNode> head; 
public:
    Store() : head(nullptr) {}
    Store(const T& data);
    

};

Trying to create a constructor that is an example of T data

template <typename T>
Store<T>::Store(const T& data) {
    head->data = data;
}

But I can't access head->data and head->next in it .I can't figure out what's wrong, I'm just learning to work with unique_ptr,so I probably don't understand something.I would be grateful for your help. The code that causes the error.

Exception thrown: write access violation.

Store<int> a(5);
1 Answers

Your Store(const T&) constructor is not creating a pointNode object to be held by the std::unique_ptr<pointNode> of the head member. The default std::unique_ptr constructor will set head to nullptr, so it never points to an actual object. Thus accessing head->data is undefined behavior.

Construct the head using std::make_unique(), like so:

Store() = delete; // or default if you need it
Store(const T& data) : head(std::make_unique<pointNode>()) {
    head->data = data;
}
Related