C++ 新运算符作用域 [英] C++ new operator scope

查看:72
本文介绍了C++ 新运算符作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我写了一段代码,我使用 new 运算符在局部作用域函数内创建一个对象,并将引用作为指针返回.

So I was writing a piece of code where I used new operator to create an object inside a local scope function and returned the reference as a pointer.

A* operator+(A that){
    int sumA = a + that.getA();
    int sumB = b + that.getB();
    return new A(sumA, sumB);
}

在我看来这是行不通的,因为对象是在本地范围内创建的,应该是临时的,但它编译并运行了.任何人都可以向我解释这一点吗?我敢肯定还有其他一些东西可以打破范围和东西.如果可能的话,你能给我一些例子吗?赞赏!

In my thought It would not work because the object was created inside the local scope and should be temporary, but it compiled and ran. Can anyone explain to me about this? I am sure there are other things that kinda have the ability of breaking the scope and stuff.. If possible, could you give me some examples? Appreciated!

推荐答案

当您说在本地范围内创建"时,您真正的意思是一个自动变量".自动变量在创建它们的作用域退出时自动销毁.

When you say "created inside local scope" what you really mean is "an automatic variable." Automatic variables are automatically destroyed when the scope in which they are created is exited from.

但是 new 不会创建自动变量.它创建一个动态分配的对象,其生命周期不受其创建范围的限制.

But new does not create an automatic variable. It creates a dynamically allocated object, whose lifetime is not bound by the scope in which it's created.

new A(sumA, sumB)创建的对象不是临时的.

这篇关于C++ 新运算符作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆