簡體   English   中英

為什么賦值運算符調用構造函數?

[英]Why does assignment operator call constructor?

我只是在玩弄了解智能指針並嘗試制作我的但我遇到的情況我並不完全理解。 這是代碼:

#include <iostream>
template <class T>
class Holder
{
private:
        T * obj;
public:
        Holder(T * tt) : obj(tt) 
        {
                std::cout << "ctor : " << tt->dummy << std::endl;
        }
        T * operator -> ()
        {
                return obj;
        }
        operator bool()
        {
                return obj;
        }
        T * const get() const
        {
                return obj;
        }
        void reset() {swap(0);}
        void swap(T * other)
        {
                obj = other;
        }
        Holder & operator = (const Holder& holder)
        {
                obj = holder.get();
                return *this;
        }
        Holder(const Holder & holder) : obj(holder.get()) {} 
};

class A
{
public:
        int dummy;
        A(int a) : dummy(a) {}
};

int main ()
{
        A * a = new A(1);
        Holder<A> holder(a);
        A * b = new A(2);
        holder = b;

        std::cout << holder->dummy << std::endl;

        return 0;
} 

代碼編譯並在holder = b;的行上holder = b; Holder類的構造函數被調用。 我以為編譯器會給出錯誤。 它不是assingment運算符,但為什么調用構造函數?

holder = b嘗試從b分配給Holder b的類型為A* ,而holder的類型為Holder<A>

Holder模板定義來自同一Holder類型的另一個實例的賦值,因此編譯器會查找從A*Holder<A>轉換 它找到構造函數,並使用它。

除非使用explicit關鍵字標記它們, 否則可能只使用一個參數的構造函數可用於隱式轉換。

調用構造函數和賦值運算符。 您可以通過在operator =打印一些內容來檢查。

發生這種情況是因為operator =被定義為采用const Holder & ,但b的類型為A * 所以首先調用Holder(T *)構造函數來創建一個臨時對象,然后通過operator =將該對象賦給holder

如果定義operator =(const T *) ,則只調用賦值運算符。

我沒有看到一個版本的賦值運算符,它采用了A *的右側

    A*        a        = new A(1);
    Holder<A> holder(a);
    A*        b         = new A(2);

    // assigning object of type A* to Holder<A>
    holder = b;

    // No appropriate assignment operator provide.
    // But a constructor is available to convert RHS parameter to correct type.
    // So compiler generates the following code:

    holder = Holder<A>(b);

    // There is an appropriate assignment operator for this.
    // So it compiles. 

你有一個構造函數采用T *。 你的assigment有一個rhs指針,所以它用該指針作為參數構造一個temp-obj,並將它賦給holder。

暫無
暫無

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

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