是否绑定到本地引用的对象会自动销毁?

pie*_*dar 2 c++ visual-c++

请考虑以下代码.

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);
}
Run Code Online (Sandbox Code Playgroud)

返回image时,被引用的对象是否会被破坏ProcessImageFile()

Nat*_*ica 6

MyImage& image = MyImage(-1); // initialized with invalid handle
Run Code Online (Sandbox Code Playgroud)

不能编译,因为你不能对非临时变量采用非const引用.如果你有

const MyImage& image = MyImage(-1); // initialized with invalid handle
Run Code Online (Sandbox Code Playgroud)

然后生命周期将延长,直到参考的生命周期结束.由于引用变量是自动对象,因此当它超出范围时,生命周期将结束.来自[basic.stc.auto]

块范围变量显式声明为寄存器或未显式声明为static或extern具有自动存储持续时间.这些实体的存储将持续到创建它们的块为止.

至于为什么Visual Studio允许这个看到非const引用绑定到临时的Visual Studio bug?