"不匹配'operator ='" g ++错误

时间:2011-03-09 22:47:26

标签: c++ g++

我有一个班级AP

template<typename T>
class AP : public std::auto_ptr<T>
{
    typedef std::auto_ptr<T> Super;
public:
    AP() : Super() { }
    AP(T* t) : Super(t) { }
    AP(AP<T>& o) : Super(o) { }
};

还有一个返回它的函数。

namespace AIR {
namespace Tests {

namespace
{

    AP<A> CreateGraph()
    {
    AP<A> top(A::Create("xyz").release());
        ...
    return top;
    }

    AP<A> top; 
    top = CreateGraph();

编译代码时

AP<A> top; 
top = CreateGraph();

我收到此错误消息

no match for ‘operator=’ in ‘top = AIR::Tests::<unnamed>::CreateGraph()()’

我将此运算符添加到AP类,但它不起作用。

AP<T>& operator=(AP<T>& o) { (*(Super*)this) = o; return *this; }

班上出了什么问题?

修改

top.reset(CreateGraph().release())解决了这个问题。

3 个答案:

答案 0 :(得分:4)

CreateGraph()按值返回,因此CreateGraph()函数调用是右值。

因为std::auto_ptr复制赋值运算符通过非const引用获取其参数,所以隐式声明的AP复制赋值运算符通过非const引用获取其参数。

非const引用只能绑定到左值,因此错误。

正如我在an answer to one of your previous questions中解释的那样,如果你想要std::auto_ptr - 就像复制一样(实际的复制构造函数通过非const引用获取其参数),你还需要实现类似于std::auto_ptr_ref

我解释了std::auto_ptr如何使用这个助手类来允许在接受的答案中复制rvalues How could one implement std::auto_ptr's copy constructor?

答案 1 :(得分:0)

不应该吗?

AP<T>& operator=(const AP<T>& o)

答案 2 :(得分:0)

如果替换

怎么办?
AP<A> top; 
top = CreateGraph();

AP<A> top(CreateGraph());