为什么shared_ptr <T>期望在T中复制/移动构造函数?

Ale*_* B. 0 c++ templates copy-constructor shared-ptr c++11

我有以下代码:

#include <memory>

using namespace std;

template<typename U> class A;

template<typename U>
class B
{
    private:
        shared_ptr<const A<U>> _a;
    public:
        B (shared_ptr<const A<U>> __a) {
            _a = __a;
        }
};

template<typename U>
class A
{
    public:
        B<U> foo () const {
            return { make_shared<const A<U>> (this) };
        }
};

int
main ()
{
    A<int> a;
    B<int> b = a.foo ();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

G ++ 4.8.0和Clang 3.3svn报告该类A没有复制或移动构造函数.例如,G ++打印以下消息:

/home/alessio/Programmi/GCC/include/c++/4.8.0/ext/new_allocator.h:120:4: error: no      matching function for call to ‘A<int>::A(const A<int>* const)’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
  ^
/home/alessio/Programmi/GCC/include/c++/4.8.0/ext/new_allocator.h:120:4: note:  candidates are:
prova.cpp:19:7: note: constexpr A<int>::A()
 class A
       ^
prova.cpp:19:7: note:   candidate expects 0 arguments, 1 provided
prova.cpp:19:7: note: constexpr A<int>::A(const A<int>&)
prova.cpp:19:7: note:   no known conversion for argument 1 from ‘const A<int>* const’ to    ‘const A<int>&’
prova.cpp:19:7: note: constexpr A<int>::A(A<int>&&)
prova.cpp:19:7: note:   no known conversion for argument 1 from ‘const A<int>* const’ to  ‘A<int>&&’
Run Code Online (Sandbox Code Playgroud)

是什么原因?

Ker*_* SB 5

你需要说:

return { make_shared<const A<U>>(*this) };
//                              ^^^
Run Code Online (Sandbox Code Playgroud)