通过ref传递vs传递指针 [英] pass by ref vs pass by pointer

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

问题描述

大家好,


区别b / w通过ref传递并通过C ++中的指针传递

你将对象传递为args ..


干杯..

HI all,

Whats the difference b/w pass by ref and pass by pointer in C++ when
ur passing objects as args..

Cheers..

推荐答案

Radde写道:
什么是差异b / w通过ref传递并通过C ++中的指针传递
你将对象作为args传递..
Whats the difference b/w pass by ref and pass by pointer in C++ when
ur passing objects as args..




引用始终引用有效对象,根据语言规则。

不同的是,当在函数内部时,如果参数是ref,

你可以依赖它是一个真实的对象。如果它是指针,它可以使

无效值或为空。


V



A reference always refers to a valid object, according to language rules.
The difference is that when inside a function, if the argument is a ref,
you can rely upon it being a real object. If it''s a pointer, it can have
an invalid value or be null.

V


Victor Bazarov写道:
Victor Bazarov wrote:
Radde写道:
Radde wrote:
在C ++中传递引用和传递指针之间有什么区别?
当您将对象作为参数传递时。
根据语言规则,引用始终引用有效对象。
不同之处在于,当在函数内部时,如果参数是引用,
你可以信赖它是一个真实的物体。
What''s the difference between pass by reference and pass by pointer in C++
when you are passing objects as arguments.
A reference always refers to a valid object, according to language rules.
The difference is that, when inside a function, if the argument is a reference,
you can rely upon it being a real object.



cat main.cc
#include< iostream>


void f(const int& r){

std :: cout<< r = << r<< std :: endl;

}


int main(int argc,char * argv []){


int * p = 0;

int& r = * p;

f(r);


返回0;

}

g ++ -Wall -ansi -pedantic -o main main.cc
。/ main
分段错误(核心转储)

如果它是指针,它可能有一个无效值或者为空。


cat main.cc #include <iostream>

void f(const int& r) {
std::cout << "r = " << r << std::endl;
}

int main(int argc, char* argv[]) {

int* p = 0;
int& r = *p;
f(r);

return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main Segmentation fault (core dumped)
If it''s a pointer, it can have an invalid value or be null.



E. Robert Tisdale写道:
E. Robert Tisdale wrote:
Victor Bazarov写道:
Victor Bazarov wrote:
Radde写道:
Radde wrote:
有什么区别?当您将对象作为参数传递时,通过引用传递并通过指针传递

What''s the difference between pass by reference and pass by pointer
in C++
when you are passing objects as arguments.



根据语言规则,引用始终引用有效对象。
不同之处在于,当在函数内部时,如果参数是
引用,那么你可以依赖它作为一个真实的对象。


A reference always refers to a valid object, according to language rules.
The difference is that, when inside a function, if the argument is a
reference,
you can rely upon it being a real object.


[。 ..example调用未定义的行为已删除...]


[...example invoking undefined behaviour removed...]




我们正在讨论具有已定义行为的有效程序。



We''re are talking valid programs with defined behaviour here.


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

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