C++ Smart Pointers erroring

So I tried getting around the smart pointer, but I just can't get it working!

#include <iostream>
#include <queue>
#include <Windows.h>

int main()
{
    std::unique_ptr<std::queue<int>> s;
    s->push(14);
    s->push(2);
    for (int i = 0; i < s->size(); i++)
    {
        std::cout << s->front();
        std::cout << std::endl;
        std::cout << s->back();
        std::cout << std::endl;
    }
    Sleep(1500);
}

What am I doing wrong?

Upvotes: 0

Views: 77

Answers (1)

JHBonarius
JHBonarius

Reputation: 11271

You're missing the <memory> include in your header. Then you are creating a pointer, but no object where it's pointing to. Try

#include <iostream> // std::cout
#include <queue> // std::queue
#include <Windows.h> // Sleep
#include <memory> // std::unique_ptr & std::make_unique

int main()
{
    // next line returns an std::unique_ptr<std::queue<int>>, hence the 'auto'
    auto s = std::make_unique<std::queue<int>>();
    s->push(14);
    s->push(2);

    std::cout << s->front() << "\n";
    std::cout << s->back() << "\n";

    Sleep(1500);
    return 0;
}

Live demo

Upvotes: 3

Related Questions