复制构造函数和防御性复制 [英] Copy constructors and defensive copying

查看:225
本文介绍了复制构造函数和防御性复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 复制构造函数

What is a copy constructor?

有人可以分享一个小例子,可以帮助理解 防御性复制原则 吗?

Can someone share a small example that can be helpful to understand along with defensive copying principle?

推荐答案

以下是一个很好的例子:

Here's a good example:

class Point {
  final int x;
  final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point(Point p) {
    this(p.x, p.y);
  }

}

注意构造函数 Point(Point p)获取 Point 并复制它 - 这是一个复制构造函数

Note how the constructor Point(Point p) takes a Point and makes a copy of it - that's a copy constructor.

这是防御性副本,因为原来的 Point 通过索取副本来保护其免受更改。

This is a defensive copy because the original Point is protected from change by taking a copy of it.

现在:

// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

请注意,这不一定是创建对象的正确方式。但是,这是一种良好方式来创建对象,以确保您不会偶然对同一对象进行两次引用。显然,如果这是你想要实现的目标,这只是一件好事。

Note that this is not necessarily the correct way of creating objects. It is, however, a good way of creating objects that ensures that you never have two references to the same object by accident. Clearly this is only a good thing if that is what you want to achieve.

这篇关于复制构造函数和防御性复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆