简体   繁体   中英

non-const lvalue reference to type '' cannot bind to a temporary of type ' *'

Demo code

In file A:

class Queuetest{
...
queue<myclass>* mMyQueue = new queue<myclass>;

void addMyclass(myclass& myclassobject){
    mMyQueue->push(myclassobject);
}
...
};

In file B:

...
Queuetest* mQueuetest = new Queuetest();

mQueuetest->addMyclass(new myclass(...));
...

So the compile tell me :

reference to type 'myclass' could not bind to an rvalue of type 'myclass *'

Some similar case give me the reason:

The C++ standard does not allow the binding of an anonymous temporary to a reference, although some compilers allow it as an extension. (Binding to a const reference is allowed.)

But there is no way to show me how to solve it;

I want to use a queue to control my object, and make the object work like a FIFO; add the new one, and pop the last one, releasing the memory for that object automatically;

Is there a good way to do this?

At least use the const qualifier

void addMyclass( const myclass& myclassobject){
    mMyQueue->push(myclassobject);
}

Or overload the function like

void addMyclass(myclass&& myclassobject){
    mMyQueue->push(myclassobject);
}

And instead of

mQueuetest->addMyclass(new myclass(...));

use

mQueuetest->addMyclass(myclass(...));

because the queue is declared as storing objects of the type myclass instead of pointers to objects.

queue<myclass>* mMyQueue = ...
      ^^^^^^^

Also it is unclear why you are using a pointer to std::queue as a data member.

queue<myclass>* mMyQueue = new queue<myclass>;

Just declare the data member like

queue<myclass> mMyQueue;

Here is a demonstrative program.

#include <iostream>
#include <queue>

struct myclass
{
};

class Queuetest
{
private:
    std::queue<myclass> mMyQueue;

public:
    void addMyclass( const myclass &myclassobject )
    {
        std::cout<< "void addMyclass( const myclass &myclassobject )\n";
        mMyQueue.push(myclassobject);
    }

    void addMyclass( myclass &&myclassobject )
    {
        std::cout<< "void addMyclass( myclass &&myclassobject )\n";
        mMyQueue.push(myclassobject);
    }
};

int main()
{
    Queuetest test;

    test.addMyclass( myclass() );

    myclass m;

    test.addMyclass( m );
}

Its output is

oid addMyclass( myclass &&myclassobject )
void addMyclass( const myclass &myclassobject )

您正在将其传递给指针而不是实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM