开发者

'no matching function for call to' error with g++ : constructor or operator = not matching?

开发者 https://www.devze.com 2023-02-18 11:47 出处:网络
I have a assignment operator. AP<T>& operator=(AP<T>& o) {Super::operator=(o); return *this; }

I have a assignment operator.

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

When I expect the g++ compiler finds this operator for this code.

AP<System> to = System::Create();

I got compilation error.

no matching function for call to ‘H::AP<H::System>::AP(H::AP<H::System>)’
ap.cpp:13: note: candidates are: H::AP<T>::AP(H::AP<U>&) [with U = H::System, T = H::System]
ap.cpp:12: note:                 H::AP<T>::AP(H::AP<T>&) [with T = H::System]
ap.cpp:11: note:                 H::AP<T>::AP(T*) [with T = H::System]

Why is this? MSVC compiles this code without problem.

The source is as follows.

#include <memory>

namespace H {

template<typename T>
class AP : public std::auto_ptr<T>
{
    typedef std:开发者_Go百科:auto_ptr<T> Super;
public:
    template<typename U> AP<T>& operator=(AP<U>& o) { Super::operator=(o.release()); return *this; }
    AP<T>& operator=(AP<T>& o) { Super::operator=(o); return *this; }
};

class System {
public:
    static AP<System> Create(); 
};

AP<System> System::Create()
{
    AP<System> a(new System()); 
    return a;
}

int main()
{
    AP<System> to = System::Create();
}
};

ADDED

With AP(const AP<T>& o) : Super(o) { }, I got those errors.

ap.cpp: In copy constructor ‘H::AP<T>::AP(const H::AP<T>&) [with T = H::System]’:
ap.cpp:33:   instantiated from here
ap.cpp:12: error: passing ‘const H::AP<H::System>’ as ‘this’ argument of ‘std::auto_ptr<_Tp>::operator std::auto_ptr_ref<_Tp1>() [with _Tp1 = H::System, _Tp = H::System]’ discards qualifiers

ADDED2

I don't know it's the best solution, but this code seems to work.

int main()
{
  H::AP<H::System> tox(H::System::Create().release());
  return 0;
}


AP<System> to = System::Create(); looks for a copy constructor as Adam said.

Using const will solve your problem. Apart from that temporaries cannot be bound to non-const references.

For example:

AP<System> &ref = AP<System>(); 

won't compile on gcc if the parameter of your copy c-tor is not a reference to const. However on MSVC++ the above code would compile because MSVC++(2008 or before) allows temporaries to get bound to non-const reference (evil extension).

However if you try to replicate auto_ptr's copy c-tor you need to implement something similar to auto_ptr_ref (in order to allow copying temporary auto_ptr objects)


It's looking for a copy constructor, not an operator=: read the error message more carefully. Your copy constructor is not defined correctly: you need to defined it as a const reference:

AP(const AP<T>& o) : Super(o) { }
// ^^^^^
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号