c++ - "no match for ‘operator=’ "g++ 错误

标签 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; }

类(class)有什么问题?

编辑

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

最佳答案

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

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

非常量引用只能绑定(bind)到左值,因此会出现错误。

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

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

关于c++ - "no match for ‘operator=’ "g++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5253243/

相关文章:

c# - Marshal.AllocHGlobal 正在分配比预期更多的内存

c++ - 为什么 g++/ld 内存不足?

c++ - 使用 g++ 进行 sse 内联汇编

c++ - Linux LibdvbV5 EIT 抢夺 - 天数不够

c++ - 从 dtor 安全地抛出异常

c++ - 在clang++与g++中除以复数<double>

类中的 C++ 映射,如何创建成员访问器

C++11 嵌套 lambda 编译段错误

c++ - 在 Xcode 4 中使用 ccache

c++ - 尝试使用 g++ 为 64 位 Windows 编译 .cpp