2015-10-08 29 views
2

請考慮以下代碼。綁定到本地引用的對象是否自動被破壞?

struct MyImage 
{ 
    MyImage(const int handle); 
    MyImage(const CString& filePath); 
    virtual ~MyImage(); 

    void Process(); 
    void SaveAs(const CString& filePath); 

    // No copying! 
    MyImage(const MyImage& other) = delete; 
    MyImage& operator=(const MyImage& other) = delete; 
} 

void ProcessImageFile(const CString& inFilePath, const CString& outFilePath) 
{ 
    MyImage& image = MyImage(-1); // initialized with invalid handle 

    if (DecryptionRequired()) 
    { 
     const CString tempFilePath = ::GetTempFileName(); 
     Decrypt(inFilePath, tempFilePath); 
     image = MyImage(tempFilePath); 
     _tremove(tempFilePath); 
    } 
    else 
    { 
     image = MyImage(inFilePath); 
    } 

    image.Process(); 
    image.SaveAs(outFilePath); 
} 

image引用的對象時ProcessImageFile()回報破壞?

+2

注意,該代碼是在標準C++無效的,所以這是一個Visual-C++具體的問題。 – Brian

+2

@Brian只是爲了好奇,哪部分是非標準的? – user463035818

+4

@ tobi303將一個非常量左值引用綁定到一個右值 – Brian

回答

6
MyImage& image = MyImage(-1); // initialized with invalid handle 

不應編譯,因爲您不能對非臨時變量採用非常量引用。如果你有

const MyImage& image = MyImage(-1); // initialized with invalid handle 

然後,延長生命期將延長,直到引用的生命期結束。由於引用變量是一個自動對象,當它超出作用域時,它的生命週期將結束。 From [basic.stc.auto]

塊顯式聲明的變量顯式聲明的變量聲明爲static或extern具有自動存儲時間。這些實體的存儲會持續到創建它們的塊退出。

至於爲什麼Visual Studio是讓這個看Non-const reference bound to temporary, Visual Studio bug?

+0

什麼時候我們寧願寫'const MyImage&image = MyImage(-1); '而不是'const auto image = MyImage(-1);'? –

+0

@JohanLundberg編寫C++ 03或以下兼容代碼時。 – dascandy

+0

對,但我的意思是;爲什麼使用引用來保存返回值? –