2016-03-05 34 views
0

第二个const在下面的结构中做了什么? (这只是一个示例函数)。const Class * const Function()第二个const做什么?

我明白,第一个const使函数返回一个常量对象。但我无法弄清楚标识符前的const是什么。

首先,我虽然知道它返回一个常量指针给一个常量对象,但我仍然可以重新指定返回的指针,所以我猜测事实并非如此。

const SimpleClass * const Myfunction() 
{ 
    SimpleClass * sc; 
    return sc; 
} 
+4

http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int -const –

+1

It * does *返回一个常量指针给一个常量对象。您可以将该指针的*值*复制到非const变量。 (它与const int f(){return 0;}的原理相同。int main(){int x = f(); x = 1;}'。) – molbdnilo

+0

想要另一个* const *?将它添加到MyFunction()行的末尾。 ;) – tofro

回答

3
const SimpleClass * const Myfunction() 
{ 
    return sc; 
} 

decltype(auto) p = Myfunction(); 
p = nullptr; // error due to the second const. 

但事实是,没有多少人使用decltype(自动),而你的函数将被正常调用,如:

const SimpleClass *p = Myfunction(); 
p = nullptr; // success, you are not required to specify the second const. 

const auto* p = Myfunction(); 
p = nullptr; // success, again: we are not required to specify the second const. 

而且......

const SimpleClass * const p = Myfunction(); 
p = nullptr; // error 

const auto* const p = Myfunction(); 
p = nullptr; // error 
+0

谢谢,现在它变得更有意义。 –

1

第二个const表示返回的指针本身是恒定的,而第一个const表示内存不可修改。

返回的指针是临时值(右值)。这就是为什么无论它是否为const也无所谓,因为无论如何都不能修改:Myfunction()++;是错误的。一种“感觉”第二个const的方法是使用decltype(auto) p = Myfunction();并尝试修改pJosé指出。

您可能会感兴趣的Purpose of returning by const value?What are the use cases for having a function return by const value for non-builtin type?

相关问题