什么是值和引用语义以及区别 [英] what is value- and reference semantics and the difference

查看:50
本文介绍了什么是值和引用语义以及区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是值语义和引用语义,它们之间有什么区别?你能用 c 中的例子给我看吗.

What is value semantics and reference semantics and what is the difference between them? Can you please show me with an example in c.

我猜在引用语义中,你只是发送一个指向另一个函数的指针,然后它是引用语义?我发现很难理解什么是值语义?如果我只使用 int 作为参数,然后假设从该函数返回一个 int,那么该函数使用值语义?副作用如何影响这一点?肯定还有其他值语义的例子,然后我提到了我是否正确.你能给我举个例子吗?如果函数将指针作为参数并且函数返回值是 int,那么该函数是否同时使用了引用语义和值语义?

I guess in reference semantics that you just send an pointer to another function then it is reference semantics? I find it hard to grasp what value semantics is? If I only use an int as an argument and then let say return an int from that function then the function uses value semantics? And how does side effects affect this? There must be other examples of value semantics then I mentioned if I were right about it. Can you please give me examples of that. If a function takes a pointer as argument and the functions return value is an int, does the function make use of both reference- and value semantics?

推荐答案

在引用语义中,参数指的是原始对象,用于读取或写入.

In the reference semantic, an argument refers to the original object, being it for reading or for writing.

在值语义中,参数只是对象的值,即副本而不是原始值.当然,如果你用一些副作用改变这个副本,原始元素保持不变.

In the value semantic, an argument is just the value of an object, i.e. a copy instead of the original. Of course, if you alter this copy with some side effects, the original element remains unchanged.

传值示例:

int f(int a)   /* argument a is passed by value (local variable containing a copy)  */ 
{
    a++;      /* increments the local variable */
    return (a+5);   /* return a value */  
}

int main (int ac, char**av) {
    int b=7, c; 
    c = f(b);  /* b will be copied. The original value is unchanged */
    printf ("b=%d c=%d\n", b, c);  /* prints 7 and 13 */
}

引用传递示例:

int fr(int* pa)   /* argument pa is a pointer refering to original value  */ 
{
    *pa+=1;      /* increments value pointed to (the original variable) */
    return (*pa+5);   /* return by value */  
}

int main (int ac, char**av) {
    int b=7, c; 
    c = fr(&b);  /* The original value in b is changed */
    printf ("b=%d c=%d\n", b, c);  /* prints 8 and 13 */
}

通过引用返回不太明显.例如,Tt 用于返回作为参数接收的引用或与之相关的引用.或对动态分配对象的引用.

Returning by reference is less obvious. Tt's used for example to return a reference received as argument, or related to it. Or a reference to a dynamically allocated object.

这篇关于什么是值和引用语义以及区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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