C++ 通过作用域销毁变量
C++ Destroying Variables via Scoping
在 C++ 中创建具有空作用域(如下所示)的 'temporary' 对象以确保它们立即被销毁是否安全或可接受的做法?
{
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 ...
在 C++ 中创建具有空作用域(如下所示)的 'temporary' 对象以确保它们立即被销毁是否安全或可接受的做法?
{
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 ...