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

c – 作为函数返回值返回的局部变量(堆栈)

发布时间:2020-12-16 10:37:46 所属栏目:百科 来源:网络整理
导读:以下是在互联网上找到的朋友功能的示例: #include iostreamusing namespace std;class Rectangle { int width,height; public: Rectangle() {} Rectangle(const Rectangle r) { width = r.width; height = r.height; cout "copyn"; } Rectangle (int x,int
以下是在互联网上找到的朋友功能的示例:

#include <iostream>
using namespace std;

class Rectangle {
    int width,height;
  public:
    Rectangle() {}
    Rectangle(const Rectangle &r) { 
        width = r.width; 
        height = r.height;
        cout << "copyn";
    }
    Rectangle (int x,int y) : width(x),height(y) {}
    int area() {return width * height;}
    friend Rectangle duplicate (const Rectangle&);
};

Rectangle duplicate (const Rectangle& param)
{
  Rectangle res;
  res.width = param.width*2;
  res.height = param.height*2;
  return res;
}

int main () {
  Rectangle foo;
  Rectangle bar (2,3);
  foo = duplicate (bar);
  cout << foo.area() << 'n';
  return 0;
}

输出:

24

请注意,朋友“duplicate”函数创建一个局部变量并作为返回值返回给调用者.这不应该是一个局部变量,并在此堆栈上分配?一旦“重复”完成执行,它不应该被销毁吗?这个例子好吗?

谢谢.

解决方法

想想常规类型:

int getInt(void) {
    int a = 5:
    return a;
}

该函数并不真正返回局部变量a.相反,它返回一个副本.同样,函数不返回res,而是复制它.

在实践中,编译器可能会检测您的函数并通过避免复制Rectangle来优化函数.

要观察构造函数调用,请使用

g++ -fno-elide-constructors foo.cpp -o foo

你必须disable return value optimization for g++(-fno-elide-constructors),这是一个非常基本的优化,即使使用-O0也可以打开.

(编辑:李大同)

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

    推荐文章
      热点阅读