Reputation: 683
Is it safe or acceptable practice to create 'temporary' objects in C++ with an empty scope (such as the following), in order to ensure they are immediately destroyed?
{
SingularPurpose singular(&ptr_to_something);
}
Upvotes: 2
Views: 76
Reputation: 48665
Yes this is perfectly acceptable practice and can be very useful for more than just individual objects. For example locking shared resources while some operations are performed and unlocking it automatically when it goes out of scope:
// 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 ...
Upvotes: 5
Reputation: 477680
Your scope isn't empty. It contains the declaration of singular
.
That's perfectly OK, but...
...there's no need to create a variable; you can just create a temporary object (which is not a variable):
SingularPurpose(&ptr_to_something);
Upvotes: 6