在 C++ 中创建具有空范围(如下所示)的“临时”对象以确保它们立即被销毁是安全的还是可接受的做法?
{
SingularPurpose singular(&ptr_to_something);
}
在 C++ 中创建具有空范围(如下所示)的“临时”对象以确保它们立即被销毁是安全的还是可接受的做法?
{
SingularPurpose singular(&ptr_to_something);
}
您的范围不为空。它包含 的声明singular
。
这完全没问题,但是...
...无需创建变量;您可以只创建一个临时对象(不是变量):
SingularPurpose(&ptr_to_something);
是的,这是完全可以接受的做法,并且不仅对单个对象非常有用。例如,在执行某些操作时锁定共享资源,并在超出范围时自动解锁:
// normal program stuff here ...
// introduce an open scope
{
std::lock_guard<std::mutex> lock(mtx); // lock a resource in this scope
// do stuff with the resource ...
// at the end of the scope the lock object is destroyed
// and the resource becomes available to other threads
}
// normal program stuff continues ...