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 } }每个大括号表示一个独立的块 ...
随机推荐
- 成都Uber优步司机奖励政策(4月13日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
- day5 if while for
.注意点: ctrl + n 自动补全 18行报错,直接定位18行 逻辑运算符and or not 复合赋值运算符 += .if-elif 判断星期几 猜拳游戏 .while循环 )3大执行流程 )什 ...
- 【SpringCloud】第十二篇: 断路器监控(Hystrix Turbine)
前言: 必需学会SpringBoot基础知识 简介: spring cloud 为开发人员提供了快速构建分布式系统的一些工具,包括配置管理.服务发现.断路器.路由.微代理.事件总线.全局锁.决策竞选. ...
- .NET工程师 技能清单
第一次写博客,先说自己对自己的职业定位.NET全栈跨语言工程师 .首先说明自己是微软的狂热粉丝,几乎所有技术都在.NET下进行. 接下来对微软目前的.NET上的技术进行进一步了解,列出一个清单或者说是 ...
- Javascript 初学笔记
变量作用域 自 ES2015 起,JS 引入let 和 const 关键词定义变量的块作用域(Block Scope). var 仅支持全局作用域(Global Scope)和函数作用域(Functi ...
- DX孟虎点评新兴市场:巴西俄罗斯火爆背后
[亿邦动力网讯]4月3日消息,在第九届中国中小企业电子商务大会暨2014中国(河南)跨境贸易电子商务峰会上,DX公司CEO孟虎对新兴市场做了详细的分析,指出在当今的跨境电商环境下,北美.西欧作为电商成 ...
- Python模块random使用详情
python常用模块目录 1.random.random()#用于生成一个0到1的随机浮点数:0<= n < 1.0 import random mcw = random.random() ...
- scrum立会报告+燃尽图(第三周第五次)
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2286 项目地址:https://coding.net/u/wuyy694 ...
- NumPy常用函数总结
转载:https://www.cnblogs.com/hd-chenwei/p/6832732.html NumPy库总包含两种基本的数据类型:矩阵和数组,矩阵的使用类似Matlab,本实例用得多的是 ...
- Qt多线程-QThread
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:Qt多线程-QThread 本文地址:http://techieliang.com/2 ...