关于const参数和函数的快速问题 [英] Quick question on const parameters and functions

查看:92
本文介绍了关于const参数和函数的快速问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解在函数声明中使用 const 的重要性,但我注意到我可以使用某些输入的东西。



以下代码段无错误编译

  bool  Foo( const   char  * str)
{
if (str = nullptr ){ return false ; } // 故意重新分配
}



但是

  bool  Foo( char  *  const  str)
{
if (str = nullptr ){ return false ; } // 故意重新分配
}



抛出一个赋值错误。



从编译器的角度来看,这两个函数调用有什么区别?

我猜我正在寻找关于神秘的 const 的一点澄清。

解决方案

  char  *  const  str 





声明一个const指针。因此,指针是不可变的,并且初始化的地址值不能改变。它不能指向另一个变量。它指向的变量可能会改变。



所以

 str =  nullptr  

是不允许的。



但是:



  const   char  * str 





声明一个指向const的指针。因此指针可能会改变,但它指向的变量可能不是。



所以

 str =  nullptr  







http://www.thegeekstuff.com/2012/06/c-constant-pointers/ [ ^ ]



http://www.parashift.com/c++-faq/const-correctness.html [ ^ ]


I understand the importance of using const in function declarations but I noticed something that I could use some input on.

The following snippet compiles without error

bool Foo(const char* str)
{
    if ( str = nullptr ) { return false; } //Intentional reassignment
}


However

bool Foo(char* const str)
{
    if ( str = nullptr ) { return false; } //Intentional reassignment
}


Throws an assignment error.

From the eye of compiler, what is the difference between these two function calls?
I guess I am looking for a little clarification on the enigmatic const.

解决方案

char* const str



Declares a const pointer. Thus the pointer is immutable and the address value it is initialised with cannot be changed. It can't be pointed to another variable. The variable it points to may be changed.

So

str = nullptr

is not allowed.

But:

const char* str



declares a pointer to a const. Thus the pointer may be changed but the variable it points to may not be.

So

str = nullptr

is allowed.


http://www.thegeekstuff.com/2012/06/c-constant-pointers/[^]

http://www.parashift.com/c++-faq/const-correctness.html[^]


这篇关于关于const参数和函数的快速问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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