Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::queue does not want to push()

Tags:

c++

This is a simple class and simple test function:

#include <queue>
#include <string>

namespace {
    using namespace std;
}

class NameStream {
    queue<string> stream;

public:
    string operator * () { return stream.front(); }
    NameStream &operator ++(int) { stream.pop(); return *this; }
    NameStream &operator ++() { stream.pop(); return *this; }
    NameStream &operator <<(string name) { stream.push(name); }

    operator bool() { return !stream.empty(); }
};

inline void nameStreamTest() {
    NameStream &stream = *new NameStream;

    stream << "hi" << "hey" << "hoy";

    while (stream) {
        printf("%s\n", (*stream++).c_str());
    }
}

It falls in

NameStream &operator <<(string name) { stream.push(name); }

inside queue's push procedure, here is the stack beyond my code:

#0  0x000b5079 in std::deque<std::string, std::allocator<std::string> >::push_back at stl_deque.h:1055
#1  0x000b50f2 in std::queue<std::string, std::deque<std::string, std::allocator<std::string> > >::push at stl_queue.h:204
#2  0x000b511c in NameStream::operator<< at NameStream.h:24
#3  0x000b520f in nameStreamTest at NameStream.h:32

My experience fails in this case. What am I doing wrong?

P.S.:

NameStream &stream = *new NameStream;

Is used to clear off location of

stream

object at address (offset?) 0x7d (!) which causes same exception.

like image 687
Zero.Arcan Avatar asked Feb 25 '23 03:02

Zero.Arcan


1 Answers

Put a return statement at the end of your function.

NameStream &operator <<(string name) { stream.push(name); return *this; }

Add: Not returning a valid reference/value (when needed) will cause a UB and that will cause hidden crashes or bad behavior which are often hard to debug (as in your case). So never ignore a compiler warning if it generates any.

like image 81
iammilind Avatar answered Mar 07 '23 00:03

iammilind