考虑以下代码。
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/