加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

我可以在不结束块的情况下终止C变量的范围吗?

发布时间:2020-12-16 09:32:55 所属栏目:百科 来源:网络整理
导读:我想做类似以下模式的事情: T* const pT = findT();// Do some workT* const pT2 = new T( *pT );// Mutate the object pT2 refers todelete pT;// At this point,I want the scope of pT to end.// I do not want the scope of pT2 to end 我知道我可以通
我想做类似以下模式的事情:

T* const pT = findT();
// Do some work
T* const pT2 = new T( *pT );
// Mutate the object pT2 refers to
delete pT;
// At this point,I want the scope of pT to end.
// I do not want the scope of pT2 to end

我知道我可以通过结束一个块结束范围,但它最终会像这样结束:

T* pT2 = 0;
{
    T* const pT = findT();
    // Do some work
    pT2 = new T( *pT );
    // Mutate the object pT2 refers to
    delete pT;
}

这会导致pT2失去其const限定符,因为我必须在声明之后分配它.

我想要我的蛋糕,我也想吃它,我想要明确的常量和适当的范围!

除了结束一个块之外,还有什么方法可以结束变量的范围吗?如果没有,有没有计划扩展标准来支持这个?

解决方法

你可以使用lambdas:

T* const pT = []() -> T* {
    T* pT;
    // Do whatever the hell you want with pT
    return pT;
}();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读