簡體   English   中英

使用值初始化訪問構造函數?

[英]Accessing constructor with value initialization?

因此,根據本文 ,符號A()new A()導致值初始化。 據我了解,兩種表示法都應轉換為默認初始化

如果T是沒有默認構造函數或用戶提供或刪除的默認構造函數的類類型,則該對象將被默認初始化;

從它們應該引起相同的行為。 然后,為什么這樣:

class Image
{
public:
    Image();
    virtual ~Image();

protected:
    std::string _filePath;

protected:
    // noncopyable
    Image(const Image& rImg);
    Image& operator=(const Image&);
    bool initWithImageFileThreadSafe(const std::string& fullpath);

};

int main()
{
    auto a = new Image(); //Works
    auto aa = Image(); //Error: inaccessible constructor
}

當你做

auto a = new Image(); //Works

您創建一個Image動態和a與它的指針初始化。 這很好,因為它是Image直接初始化。

當你做

auto aa = Image(); //Error: inaccessible constructor

在C ++ 17之前的版本中,您調用復制初始化,該初始化使用一個值初始化的臨時Image作為值來初始化aa 由於您的復制構造函數被標記為protected因此實際上不允許這樣做,並且會出現編譯器錯誤。 即使可以刪除此副本,您仍然需要可訪問的副本/移動構造函數。

在C ++ 17之后,這里實際上沒有生成任何臨時文件,並且編譯器實質上將代碼轉換為Image aa{}; 這樣就消除了該副本,並且不需要可訪問的副本/移動構造函數。

暫無
暫無

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

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