绑定到局部引用的对象是否自动销毁
Are objects bound to local references automatically destructed?
考虑以下代码:
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?
相关文章:
- 是否需要删除包含对象的"pair"?
- 是否删除在对象构造过程中创建的对象
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 在这种情况下,java对象是否可以调用本机函数
- 返回指向对象的指针的函数调用是否为 prvalue?
- 具有引用成员的结构是否具有唯一的对象表示形式
- 对象初始化中是否允许指向此成员的指针?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 是否可以使用一个类来控制 C++ 中另一个类的对象?(阿杜伊诺)
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- QFileSystemModel 对象是否会被删除?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 线程调用的函数对对象删除是否安全?
- 将对象的字节复制到数组并再次复制回来是否安全
- std::memmove在同一对象之间是否始终安全
- 类对象在 c++ 中是否具有数据类型?
- 是否可以将不可复制的成员用作使对象不可复制的替代方法?