为什么按值返回的对象与方法内的对象具有相同的地址? [英] Why does an object returned by value have the same address as the object inside the method?

查看:55
本文介绍了为什么按值返回的对象与方法内的对象具有相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <array>
#include <vector>

std::vector<int> foo() {
 int i;
 std::vector<int> a(100);
 printf("%p, %p, %p\n", &i, &a, &(a[0]));
 return a;
}

int main() {
 int i;
 std::vector<int> b = foo();
 printf("%p, %p, %p\n", &i, &b, &(b[0]));
}

为什么 a b 的地址是否相同?这是某种跨堆栈框架优化吗?即使使用 -O0 选项,结果也相同。

Why do a and b have the same address for the above? Is this some kind of "cross-stack-frame" optimization? The result is the same even when I use the -O0 option.

输出:

$ vim main.cpp 
$ cc -std=c++11 -lc++ main.cpp
$ ./a.out
0x7ffee28d28ac, 0x7ffee28d28f0, 0x7ff401402c00
0x7ffee28d290c, 0x7ffee28d28f0, 0x7ff401402c00
$ 


推荐答案

这是因为复制省略/命名返回值优化(NRVO)。 foo 返回一个命名对象 a 。因此,编译器不会创建本地对象并返回它的副本,而是在调用者放置它的地方创建该对象。您可以在 https://en.cppreference.com/w/cpp/上了解有关此内容的更多信息。语言/ copy_elision 。尽管从C ++ 17开始RVO是强制性的,但NRVO不是强制性的,但是即使 -O0 的情况,您的编译器也支持它。

This is because of copy elision/named return value optimization (NRVO). foo returns a named object a. So the compiler is not creating a local object and returning a copy of it but creates the object at the place where the caller puts it. You can read more about it on https://en.cppreference.com/w/cpp/language/copy_elision. While RVO is mandatory since C++17, NRVO is not, but it looks like your compiler supports it even in case of -O0.

这篇关于为什么按值返回的对象与方法内的对象具有相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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