簡體   English   中英

為什么shared_ptr <T> 期望在T中復制/移動構造函數?

[英]Why shared_ptr<T> expects copy/move constructor in T?

我有以下代碼:

#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;
}

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>&&’

是什么原因?

您需要說:

return { make_shared<const A<U>>(*this) };
//                              ^^^

根據文檔, make_shared構造給定類型ant的新實例,然后將其包裝到shared_ptr中。 您正在嘗試構造類型為A *的A的新實例。 這是shared_ptr的構造函數,它使用指針作為參數,而不是make_shared

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM