0

I have some questions when I read some open source codes like

struct A {
    int a;
};

class C {
private:
    std::queue<A> q;

public:
    C() {
        q.emplace(1);
        q.emplace(2);
    }

    A pop1() {
        auto a = std::move(q.front());
        q.pop();
        return a;
    }

    void pop2(A&& pData) {
        pData = std::move(q.front());
        q.pop();
    }

    A pop3() {
        auto &a = q.front();
        q.pop();
        return a;
    }
};

I wonder whether move is useful in this situation(to achieve its goal to be effcient by saving copy construct). And pop3 is my version, and I think it may be more effcient by saving the move construct if using pop1.

f1msch
  • 509
  • 2
  • 12

1 Answers1

0

In case of pop3 if you first reference the value and then use pop() method then you have kind of dangling reference. First you assign a reference to object returned by front() (well - here You return the object there already by value, note that), then you delete it from queue so the reference point nowhere.

  • Yes, I wonder that too. But I build and runs it under vs17, it works well. – f1msch Mar 20 '23 at 11:12
  • 1
    @f1msch Just because it seems to work in a specific scenario doesn't mean that the code is valid, or works in general. That's the nature of [undefined behaviour](https://stackoverflow.com/a/6445794/1968). – Konrad Rudolph Mar 20 '23 at 13:43