C ++通过范围来销毁变量

时间:2016-01-13 23:29:59

标签: c++ lifetime-scoping

创建临时'是否安全或可接受的做法? C ++中具有空范围的对象(如下所示),以确保它们立即被销毁?

{
    SingularPurpose singular(&ptr_to_something);
}

2 个答案:

答案 0 :(得分:6)

  1. 您的范围不是空的。它包含singular

  2. 的声明
  3. 这完全没问题,但是......

  4. ...没有必要创建变量;你可以创建一个临时对象(它不是一个变量):

    SingularPurpose(&ptr_to_something);
    

答案 1 :(得分:5)

是的,这是完全可以接受的做法,并且对于不仅仅是单个对象非常有用。例如,在执行某些操作时锁定共享资源,并在超出范围时自动解锁:

// 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 ...