使用函数返回指针作为LValue [英] Using a Function returning apointer as LValue

查看:158
本文介绍了使用函数返回指针作为LValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能使用返回指针作为左值的函数?



例如这个函数可以工作

  int * function()
{
int * x;
return x;


int main()
{
int * x = function();
x = new int(9);
}

但不是这个

  int * function()
{
int * x;
return x;
}

int main()
{
int * x;
function()= x;
}




  1. 虽然我可以使用指针变量作为左值,为什么我不能使用返回指针作为左值的函数?

  2. 另外,当函数返回一个
    refernce,而不是一个指针,那么
    就成为一个有效的左值。

    >


解决方案

您的第一个示例并不能解释您为什么认为它确实如此。您首先将函数调用的结果存储在变量x中,然后使用新创建的数组覆盖x的值。 *(function())= 5应正确地尝试将5写入由函数内部的局部变量x指定的随机存储单元。



示例:

  int x; 

int * function()
{
return& x;


int main()
{
*(function())= 5;
printf(%d \\\
,x);
}


Why cant I used a function returning a pointer as a lvalue?

For example this one works

int* function()
{
    int* x;
    return x;
}

int main()
{
    int* x = function();
    x = new int(9);
}

but not this

int* function()
{
    int* x;
    return x;
}

int main()
{
   int* x;
   function() = x;
}

  1. While I can use a pointer variable as a lvalue, why can't I use a function returning a pointer as a lvalue?

  2. Also, when the function returns a refernce, instead of a pointer, then it becomes a valid lvalue.

解决方案

Your first sample doesn't do why I think you think it does. You first store the result of the function call in the variable x and then you override x's value with the newly created array. *(function()) = 5 should properly try to write 5 to some random memory location specified by the local variable x inside your function.

Sample:

int x;

int* function()
{
    return &x;
}

int main()
{
   *(function()) = 5;
   printf("%d\n", x);
}

这篇关于使用函数返回指针作为LValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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