2017-02-15 89 views
-1

我想我沒有理解返回const的正確想法。修改const從函數返回

如果我有一個返回const值的函數,是不是說我返回後無法更改該值?

爲什麼編譯器允許我將const轉換爲非const變量?

或者它只適用於const指針?

const int foo(int index) { 
    return ++index; 
} 

int main(){ 
    int i = foo(1); // why can I do this? 
    ++i; 

    return 0; 
} 
+0

一個'const int'可以很容易地複製,這就是將它分配給'i'時發生的情況。 'const'指針是不同的,因爲你指向*的*是'const',除非你有'const X * const',在這種情況下指針和目標都是'const'。看到[這樣的例子](http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const)的更多解釋。返回一個'const int'在任何情況下都是毫無意義的,因爲它們很便宜。 – tadman

+2

請參閱http://stackoverflow.com/questions/6299967/what-are-the-use-cases-for-having-a-function-return-by-const-value-for-non-built和http:// stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value獲取更多信息 – wkl

+0

因此,通過值返回const是沒用的? @tadman – Dannz

回答

4

你做的這相當於:

const int a = 42; // a cannot be modified 
int b = a;  // b is a copy of a... 
++b;    // and it can be modified 

換句話說,你是一個const對象的副本,並修改所述副本。


注意,返回const價值有限,EHM,值。對於內置類型,這並不重要。對於用戶定義的類型,它可以防止修改「臨時」對象,代價是防止移動語義。從C++ 11開始,建議不要返回const值。