C++编程思想 第1卷 第8章 常量 函数参数和返回值 返回const值

用const限定函数参数及返回值是常量概念容易引起混淆的一个地方
如果按值传递对象,对客户来讲,const限定没有意义
如果按常量返回用户定义类型的一个对象的值,意味着返回值不能修改
如果传递并返回地址,const将保证地址内容不会被改变

返回值讲,如果一个函数的返回值是一个常量 const
这就约定了函数框架的原变量不会被修改。
如果按值返回,变量就被制成副本,使得初值不会被返回值修改

//: C08:Constval.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Returning consts by value
// has no meaning for built-in types

int f3() { return 1; }
const int f4() { return 1; }

int main() {
  const int j = f3(); // Works fine
  int k = f4(); // But this works fine too!
} ///:~

对于内建类型来说,按值返回的是否是一个const,是无关紧要的

当处理用户定义的类型时,按值返回常量是重要的
如果一个函数按值返回一个类对象为const时,那么函数的返回值不能死一个
左值

//: C08:ConstReturnValues.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Constant return by value
// Result cannot be used as an lvalue

class X {
  int i;
public:
  X(int ii = 0);
  void modify();
};

X::X(int ii) { i = ii; }

void X::modify() { i++; }

X f5() {
  return X();
}

const X f6() {
  return X();
}

void f7(X& x) { // Pass by non-const reference
  x.modify();
}

int main() {
  f5() = X(1); // OK -- non-const return value
  f5().modify(); // OK
//!  f7(f5()); // Causes warning or error
// Causes compile-time errors:
//!  f6() = X(1);
//!  f6().modify();
//!  f7(f6());
} ///:~

当值返回一个内建类型时,const没有意义的原因是,编译器已经不让它
成为一个左值。仅当按值返回用户定义的类型对象时,才会出现问题

无输出

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81148406