2013-05-08 83 views
0

我有以下代碼:爲什麼shared_ptr <T>期望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和鏘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>&&’ 

的原因是什麼?

+0

'A'不是一個類。這是一個模板。 – 2013-05-08 12:48:22

回答

0

根據該文件,make_shared構建給定類型的螞蟻的新實例,然後把它包裝成的shared_ptr。您正嘗試使用A *類型構造A的新實例。它是shared_ptr的構造函數,它將指針作爲參數,而不是make_shared

+0

但'make_shared'如何構造新的實例?你假設在'A'類中有一個私人領域'C c';如果在'A'類中沒有任何複製/移動構造函數,它是如何構造新實例的? – 2013-05-09 06:41:53

+0

'make_shared'調用'A'類的構造函數。構造函數根據'make_shared'的參數進行選擇(當然,該對象必須以指定的方式構造)。如果你想創建一個'shared_ptr'指向一個帶有私有(禁止)拷貝構造函數的現有對象,你應該直接使用'shared_ptr'的構造函數,就像'shared_ptr >(this)'一樣。請注意,在你的情況下,你仍然擁有類「A」的默認拷貝構造函數,所以你最好寫'make_shared >(* this)',從而創建一個副本。 – Inspired 2013-05-09 09:56:35

5

你需要說:

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