簡體   English   中英

為什么C ++ auto_ptr有兩個復制構造函數和兩個賦值運算符,但是一個默認構造函數?

[英]Why does C++ auto_ptr have two copy constructors and two assignment operators but one default constructor?

為什么需要兩種形式? 謝謝

    explicit auto_ptr (T* ptr = 0) throw() 

    auto_ptr (auto_ptr& rhs) throw() 

    template<class Y>
    auto_ptr (auto_ptr<Y>& rhs) throw() 

    auto_ptr& operator= (auto_ptr& rhs) throw()

    template<class Y>
    auto_ptr& operator= (auto_ptr<Y>& rhs) throw()

它具有一個副本構造函數-非模板構造函數。

模板構造函數和賦值運算符允許對隱式存在的指針類型進行賦值:

class A {}
class B : public A {}

B * b = new B();
A * a = b;       // OK!


auto_ptr<B> b(new B);
auto_ptr<A> a = b; // *

沒有模板版本,(*)將不起作用,因為編譯器將auto_ptr<A>視為與auto_ptr<B>完全不同的類型。

因為復制構造函數不能是模板。 如果他們只有模板版本,那么編譯器將制作出無法正常工作的版本。

作業相同...我想。

為什么C ++ auto_ptr有兩個復制構造函數和兩個賦值運算符,但是一個默認構造函數?

它不是。

它有1個默認構造函數(一個帶有0個參數的構造函數)

explicit auto_ptr (T* ptr = 0) throw() 

它具有1個復制構造函數(一個從相同類型的對象進行復制的構造函數)

auto_ptr (auto_ptr& rhs) throw() 

它具有1個賦值運算符,用於分配相同類型的對象。

auto_ptr& operator= (auto_ptr& rhs) throw()

它有一個花哨的模板化構造函數,該構造函數采用其他類型的auto_ptr(這不是一個復制構造函數,它只是一個普通的構造函數(盡管它是模板化的))。

template<class Y>
auto_ptr (auto_ptr<Y>& rhs) throw() 

它具有另一個采用不同類型的自動指針的賦值運算符(因此,是另一個賦值運算符,但它不是副本賦值運算符(而是轉換賦值運算符),因為rhs具有不同的類型)。

template<class Y>
auto_ptr& operator= (auto_ptr<Y>& rhs) throw()

使用非模板版本的原因是允許將auto_ptr分配給/構造為相同類型。 存在模板版本以允許從相關但不相同的指針類型進行構造/分配。

auto_ptr <Foo> f = new Foo(); // uses raw pointer constructor
auto_ptr <Foo> f2 = f;  // uses non-templated constructor
auto_ptr <const Foo> f3 = f2; // uses templated constructor   

auto_ptr <Foo> f4 = new foo();
f2 = f4; // uses non-templated assignment operator
f3 = f2; // uses templated assignment operator

暫無
暫無

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

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