您的位置:首页 > 编程语言 > C语言/C++

读《深度探索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));
}
时间竟然更长了,很难想象:



所以,对于像这种的,不需要声明拷贝构造函数的,我们就不用画蛇添足吧,让编译器替我们默默构造就好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: