2016-03-05 75 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?

相關問題