c ++通过引用和指针传递参数 [英] c++ passing arguments by reference and pointer

查看:37
本文介绍了c ++通过引用和指针传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中

class bar
{
    int i;
    char b;
    float d;
};

void foo ( bar arg );
void foo ( bar &arg );
void foo ( bar *arg );

这是一个示例类/结构和函数
我有一些问题

this is a sample class/struct and functions
i have some Qs

  • 在 'asm', size, speed 中传递参数的第一种和第二种方式有什么区别?
  • 在每种情况下如何将参数传递给函数 foo(在指针的情况下,我知道指针被压入堆栈)
  • 在传递参数时,就效率而言(速度、大小、偏好)哪个更好?
  • 与每种传递参数的方式相对应的英特尔asm"语法是什么?

我知道最常说的现代编译器和 CPU 无关紧要"是什么意思,但如果我们谈论的是旧 CPU 或编译器呢?

i know what most say about "it doesn't matter on modern compilers and CPUs" but what if we're talking about Old CPUs or compilers?

提前致谢

推荐答案

指针和引用方法应该相当(速度、内存使用和生成的代码).

The pointer and the reference methods should be quite comparable (both in speed, memory usage and generated code).

直接传递一个类会强制编译器复制内存并将 bar 对象的副本放在堆栈上.更糟糕的是,在 C++ 中,有各种令人讨厌的位(默认复制构造函数和诸如此类)与此相关.

Passing a class directly forces the compiler to duplicate memory and put a copy of the bar object on the stack. What's worse, in C++ there are all sort of nasty bits (the default copy constructor and whatnot) associated with this.

在 C 中,我总是使用(可能是 const)指针.在 C++ 中,您可能应该使用引用.

In C I always use (possibly const) pointers. In C++ you should likely use references.

这篇关于c ++通过引用和指针传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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