以下是在互联网上找到的朋友功能的示例:
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle(const Rectangle &r) {
width = r.width;
height = r.height;
cout << "copy\n";
}
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
24
Run Code Online (Sandbox Code Playgroud)
请注意,朋友"duplicate"函数创建一个局部变量并作为返回值返回给调用者.这不应该是一个局部变量,并在此堆栈上分配?一旦"重复"完成执行,它不应该被销毁吗?这个例子好吗?
谢谢.
iBu*_*Bug 10
想想常规类型:
int getInt(void) {
int a = 5:
return a;
}
Run Code Online (Sandbox Code Playgroud)
该函数并不真正返回局部变量a.而是返回一份副本a.同样,res函数不返回,而是复制它.
实际上,编译器可能会检测您的功能并通过避免复制来优化功能Rectangle.
要观察构造函数调用,请使用
g++ -fno-elide-constructors foo.cpp -o foo
Run Code Online (Sandbox Code Playgroud)
您必须禁用g ++(-fno-elide-constructors)的返回值优化,这是一个非常基本的优化,即使使用也会打开-O0.