2017-02-15 79 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值。