绑定到局部引用的对象是否自动销毁

Are objects bound to local references automatically destructed?

本文关键字:是否 对象 局部 引用 绑定      更新时间:2023-10-16

考虑以下代码:

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);
}

ProcessImageFile()返回时,image引用的对象会被销毁吗?

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

不应该编译,因为你不能接受对临时变量的非const引用。如果你有

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

则生存期将被延长,直到引用的生存期结束。因为引用变量是一个自动对象,生命周期将在它超出作用域时结束。从[basic.stc.auto]

块作用域变量显式声明为register或未显式声明为static或extern,具有自动存储持续时间。这些实体的存储将持续到创建它们的块退出为止。

至于为什么Visual studio允许这个,请参阅非const引用绑定到临时,Visual studio bug?