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没有意义的原因是,编译器已经不让它
成为一个左值。仅当按值返回用户定义的类型对象时,才会出现问题

无输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值