c++ - 绑定(bind)到本地引用的对象是否会自动销毁?

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

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

最佳答案

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

不应编译,因为您不能对临时变量进行非 const 引用。如果你有

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

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

Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

至于为什么 Visual Studio 允许这样做,请参阅 Non-const reference bound to temporary, Visual Studio bug?

关于c++ - 绑定(bind)到本地引用的对象是否会自动销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024095/

相关文章:

c++ - 错误 "undefined reference to omp_get_wtime"

c++ - 是否可以使模板函数成为模板特化类的友元?

visual-c++ - MFC VC++ CStatic 只接收 WM_NCHITTEST

c++ - 通过 CMake 连接 fftw3 库

dll - 如何在无需将exe与lib文件重新链接的情况下更新C++ dll?

c++ - 目标文件中未解析的外部符号

c++ - TVM_SETBKCOLOR 和 TreeView_SetBkColor 未在此范围内声明?

c++ - || 的逻辑错误运算符(operator)?

c++ - cstdlib 无法使用::wcstombs 解析

c++ - 为什么没有在此范围内声明函数?