读《深度探索C++对象模型》之拷贝构造函数是否有必要明确定义?
2016-05-07 15:06
375 查看
我想,对于大部分程序员来说,一般的类都会定义构造函数/虚构函数/拷贝构造函数/赋值函数等,但是真的有必要吗,难道让编译器默认替我们定义一个不好吗,请看以下例子:
那如果我们明确声明了一个拷贝构造函数呢,时间又是如何呢?
天啊,简直差不多两倍了,这也许是编译器为我们做过优化了吧。
假如我把拷贝函数改成这样:
所以,对于像这种的,不需要声明拷贝构造函数的,我们就不用画蛇添足吧,让编译器替我们默默构造就好了。
class Point { public: Point(float x, float y, float z) { _x = x; _y = y; _z = z; } private: float _x, _y, _z; }; int main() { double dur; clock_t start, end; start = clock(); for (unsigned int i = 0; i < 10000000; i++) { Point p(0, 1, 1); Point t1(p); } end = clock(); dur = double(end - start); printf("Use time: %f\n", (dur/CLOCKS_PER_SEC)); system("pause"); return 0; }以上的类很简单,只含有三个数据变量,为了明显区分时间,因此我执行10000000次,上面的执行时间如下:
那如果我们明确声明了一个拷贝构造函数呢,时间又是如何呢?
class Point { public: Point(float x, float y, float z) { _x = x; _y = y; _z = z; } Point(const Point& rhs) { _x = rhs._x; _y = rhs._y; _z = rhs._z; } private: float _x, _y, _z; };执行时间如下:
天啊,简直差不多两倍了,这也许是编译器为我们做过优化了吧。
假如我把拷贝函数改成这样:
Point(const Point& rhs) { memcpy(this, &rhs, sizeof(rhs)); }时间竟然更长了,很难想象:
所以,对于像这种的,不需要声明拷贝构造函数的,我们就不用画蛇添足吧,让编译器替我们默默构造就好了。
相关文章推荐
- RBTree(红黑树)--C++
- AVLTree--C++
- c++ 类型转换
- C语言中如何使用宏[转]
- More Effective C++----(26)限制某个类所能产生的对象数量
- C++学习:string构造函数的bug
- 函数内部静态变量,( \\Visual C++\\ CLR \\ windows窗体应用程序 编写C++)
- C++统计字符出现的次数并输出
- C++高级编程资料汇总(参考手册+电子书+编程思想+算法分析)
- C++版简单线程池
- [C++]OOP编程基本准则
- Leetcode 18. 4Sum
- 注释转换项目(c->c++)
- C++ 操作符重载
- C++(Qt)之尽可能延后定义式的出现时间
- 高效c/c++读书笔记
- 二进制中1的个数的多种解法解析以及完整c语言代码
- C语言malloc
- c语言不使用加号实现两个数的相加
- mono嵌入C++。运行失败