C++解析(13):临时对象与const对象
0.目录
1.临时对象
2.const对象
3.类成员
4.小结
1.临时对象
一个有趣的问题——下面的程序输出什么?为什么?
#include <stdio.h>
class Test {
int mi;
public:
Test(int i) {
mi = i;
}
Test() {
Test(0);
}
void print() {
printf("mi = %d\n", mi);
}
};
int main()
{
Test t;
t.print();
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
mi = -1130582912
[root@bogon Desktop]# ./a.out
mi = -763375808
[root@bogon Desktop]# ./a.out
mi = 179227552
[root@bogon Desktop]# ./a.out
mi = 1452105392
发生了什么?
- 程序意图——在Test()中以0作为参数调用Test(int i),将成员变量mi的初始值设置为0
- 运行结果——成员变量mi的值为随机值
构造函数是一个特殊的函数:
- 是否可以直接调用?
- 是否可以在构造函数中调用构造函数?
- 直接调用构造函数的行为是什么?
答案:
- 直接调用构造函数将产生一个临时对象
- 临时对象的生命周期只有一条语句的时间
- 临时对象的作用域只在一条语句中
- 临时对象是C++中值得警惕的灰色地带
在实际的开发工程中,也许构造函数体的逻辑非常复杂,没有必要哪个构造函数都写一遍,采用代码复用的思想,提供一个私有的init()函数进行初始设置:
#include <stdio.h>
class Test {
int mi;
void init(int i)
{
mi = i;
}
public:
Test(int i) {
init(i);
}
Test() {
init(0);
}
void print() {
printf("mi = %d\n", mi);
}
};
int main()
{
Test t;
t.print();
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
mi = 0
进一步证明临时对象的生命周期只有一条语句的时间:
#include <stdio.h>
class Test {
int mi;
void init(int i)
{
mi = i;
}
public:
Test(int i) {
printf("Test(int i)\n");
init(i);
}
Test() {
printf("Test()\n");
init(0);
}
void print() {
printf("mi = %d\n", mi);
}
~Test() {
printf("~Test()\n");
}
};
int main()
{
printf("main begin\n");
Test().print();
Test(10).print();
printf("main end\n");
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
main begin
Test()
mi = 0
~Test()
Test(int i)
mi = 10
~Test()
main end
编译器的行为——现代C++编译器在不影响最终执行结果的前提下,会尽力减少临时对象的产生!!!
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
printf("Test(int i) : %d\n", i);
mi = i;
}
Test(const Test& t)
{
printf("Test(const Test& t) : %d\n", t.mi);
mi = t.mi;
}
Test()
{
printf("Test()\n");
mi = 0;
}
int print()
{
printf("mi = %d\n", mi);
}
~Test()
{
printf("~Test()\n");
}
};
Test func()
{
return Test(20);
}
int main()
{
Test t = Test(10); // ==> Test t = 10;
Test tt = func(); // ==> Test tt = Test(20); ==> Test tt = 20;
t.print();
tt.print();
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
Test(int i) : 10
Test(int i) : 20
mi = 10
mi = 20
~Test()
~Test()
可以看到,并没有调用拷贝构造函数。因为现代C++编译器在不影响最终执行结果的前提下,会尽力减少临时对象的产生。因此直接将Test t = Test(10);优化为Test t = 10;,这样就少调用了一次构造函数,提高了程序效率!
2.const对象
关于const对象的疑问——const关键字能否修饰类的对象?如果可以,有什么特性?
- const关键字能够修饰对象
- const修饰的对象为只读对象
- 只读对象的成员变量不允许被改变
- 只读对象是编译阶段的概念,运行时无效
const修饰的对象为只读对象,不能修改成员变量,否则将报错:
#include <stdio.h>
class Test
{
public:
int mj;
Test(int j);
};
Test::Test(int j)
{
mj = j;
}
int main()
{
const Test t(1);
t.mj = 2;
return 0;
}
报错信息为:
[root@bogon Desktop]# g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:19: error: assignment of data-member ‘Test::mj’ in read-only structure
C++中的const成员函数:
- const对象只能调用const的成员函数
- const成员函数中只能调用const成员函数
- const成员函数中不能直接改写成员变量的值
const成员函数的定义:
Type ClassName::function(Type p) const
类中的函数声明与实际函数定义中都必须带const关键字。
const对象只能调用const的成员函数,否则会报错:
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i);
Test(const Test& t);
int getMi()const; // 函数声明处加上const
};
Test::Test(int i)
{
mi = i;
}
Test::Test(const Test& t)
{
}
int Test::getMi()const // 函数定义处加上const
{
return mi;
}
int main()
{
const Test t(1);
printf("t.getMi() = %d\n", t.getMi());
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
t.getMi() = 1
3.类成员
关于类成员的疑问——成员函数和成员变量都是隶属于具体对象的吗?
从面向对象的角度:
- 对象由属性(成员变量)和方法(成员函数)构成
从程序运行的角度:
- 对象由数据和函数构成:
- 数据可以位于栈,堆和全局数据区
- 函数只能位于代码段
结论:
- 每一个对象拥有自己独立的属性(成员变量)
- 所有的对象共享类的方法(成员函数)
- 方法能够直接访问对象的属性
- 方法中的隐藏参数 this 用于指代当前对象
示例:
#include <stdio.h>
class Test
{
int mi;
public:
int mj;
Test(int i);
Test(const Test& t);
int getMi();
void print();
};
Test::Test(int i)
{
mi = i;
}
Test::Test(const Test& t)
{
mi = t.mi;
}
int Test::getMi()
{
return mi;
}
void Test::print()
{
printf("this = %p\n", this);
}
int main()
{
Test t1(1);
Test t2(2);
Test t3(3);
printf("t1.getMi() = %d\n", t1.getMi());
printf("&t1 = %p\n", &t1);
t1.print();
printf("t2.getMi() = %d\n", t2.getMi());
printf("&t2 = %p\n", &t2);
t2.print();
printf("t3.getMi() = %d\n", t3.getMi());
printf("&t3 = %p\n", &t3);
t3.print();
return 0;
}
运行结果为:
[root@bogon Desktop]# g++ test.cpp
[root@bogon Desktop]# ./a.out
t1.getMi() = 1
&t1 = 0x7fffe0431e30
this = 0x7fffe0431e30
t2.getMi() = 2
&t2 = 0x7fffe0431e20
this = 0x7fffe0431e20
t3.getMi() = 3
&t3 = 0x7fffe0431e10
this = 0x7fffe0431e10
可以看到,在类的成员函数当中,有一个隐含的参数,这个隐含的参数是一个指针,并且这个指针的值就是调用这个函数所对应的对象的地址。
4.小结
- 直接调用构造函数将产生一个临时对象
- 临时对象是性能的瓶颈,也是bug的来源之一
- 现代C++编译器会尽力会避开临时对象
- 实际工程开发中需要人为的避开临时对象
- const关键字能够修饰对象,得到只读对象
- 只读对象只能调用const成员函数
- 所有对象共享类的成员函数
- 隐藏的this指针用于表示当前对象
C++解析(13):临时对象与const对象的更多相关文章
- const对象,指向const对象的指针 和 const 指针
const对象: const对象声明时必须赋初值,该值在编译阶段确定,不可在程序中修改. const修饰符既可放在类型名前也可放在类型名后,通常放在类型名前.不过放在类型名后易于理解. const i ...
- c++中的const参数,const变量,const指针,const对象,以及const成员函数
const 是constant 的缩写,“恒定不变”的意思.被const 修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性.所以很多C++程序设计书籍建议:“Use const whe ...
- jquery 1.7.2源码解析(二)构造jquery对象
构造jquery对象 jQuery对象是一个类数组对象. 一)构造函数jQuery() 构造函数的7种用法: 1.jQuery(selector [, context ]) 传入字符串参数:检查该字符 ...
- 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象, const 指针和指向 const 对象的指针, const 对象的引用
[源码下载] 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象, const 指针和指向 const 对象的指针, con ...
- const对象
const对象不能引用类的非const成员函数
- c++ , const对象中的变量不能被修改
const对象中的变量不能被修改,即使const对象中的函数也不能修改该对象中的变量值 #include <iostream> using namespace std; //------- ...
- const对象默认是static的,而不是extern的
const 和 static 变量,可以放在头文件中 const对象默认是static的,而不是extern的,所以即使放在头文件中声明和定义.多个cpp引用同一个头文件,互相也没有感知,所以不会导致 ...
- 关于C++的const对象
对于const类对象,类指针, 类引用, 只能调用类的const成员函数. 1.const成员函数不允许被修改它所在对象的任何一个成员变量. 2.const成员函数能访问对象的const成员, 而其他 ...
- (1)ES6中let,const,对象冻结,跨模块常量,新增的全局对象介绍
1.let声明变量,var声明变量,而const声明的常量 2.let与var的区别 let可以让变量长期驻扎在内存当作 let的作用域是分块[ {快1 {快2 } }每个大括号表示一个独立的块 ...
随机推荐
- lamp环境搭建(centos6.9+apache2.4+mysql5.7+php7.1)
lamp环境搭建(centos6.9+apache2.4+mysql5.7+php7.1) 安装前准备:CentOS 6.9 64位 最小化安装 yum install -y make gcc gcc ...
- day 1类 对象 属性 方法
1. 解决吃啤酒鸭的问题 第一种方式(面向过程): 1)养鸭子 2)鸭子长成 3)杀 4)作料 5)烹饪 6)吃 7)卒 第二种方式(面向对象): 1)找个卖啤酒鸭的人 2)给钱 交易 3)吃 4)胖 ...
- SaltStack入门篇(五)之salt-ssh的使用以及LAMP状态设计部署
1.salt-ssh的使用 官方文档:https://docs.saltstack.com/en/2016.11/topics/ssh/index.html ()安装salt-ssh [root@li ...
- underscore.js 分析 第四天
查看underscore包含多少属性和方法 通过阅读JavaScript 获取对象的键的数组 var a = _; var arr = Object.keys(a); console.log(arr) ...
- 用Micro:bit做剪刀、石头、布游戏
剪刀.石头.布游戏大家都玩过,今天我们用Micro:bit建一个剪刀.石头.布游戏! 第一步,起始 当你摇动它时,我们希望the micro:bit选择剪刀.石头.布.尝试创建一个on shake b ...
- flask ssti python2和python3 注入总结和区别
总结一下flask ssti的注入语句 代码 import uuid from flask import Flask, request, make_response, session,render_t ...
- linux-ubuntu常用命令(深圳文鹏)
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- 【sed】常用命令
替换 替换某一整行 sed '1c hello' test #将第一行替换为hello str1替换为str2 sed 's/^str1.*/str2/' filename #以str1开头 sed ...
- Oracle集合
--union 并集 select * from emp where ename like '%A%' union select * from emp where ename like '%M%'; ...
- Python基础灬dict&set
字典dict 字典使用键-值(key-value)存储,具有极快的查找速度. dict基本操作 取值 a_dict = {'name': 'jack', 'age': 18} print(a_dict ...