Copy constructors and defensive copying

前端 未结 5 1442
梦谈多话
梦谈多话 2020-12-03 10:44

What is a copy constructor?

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

5条回答
  •  一生所求
    2020-12-03 11:43

    Copy constructors one often sees in C++ where they are needed for partly hidden, automatically invoked operations.

    java java.awt.Point and Rectangle come to mind; also very old, mutable objects.

    By using immutable objects, like String, or BigDecimal, simply assigning the object reference will do. In fact, due to the early phase of Java after C++, there still is a silly copy constructor in String:

    public class Recipe {
        List ingredients;
    
        public Recipe() {
            ingredients = new ArrayList();
        }
    
        /** Copy constructor */
        public Recipe(Recipe other) {
            // Not sharing: ingredients = other.ingredients;
            ingredients = new ArrayList();
            ingredients.addAll(other.ingredients);
        }
    
        public List getIngredients() {
            // Defensive copy, so others cannot change this instance.
            return new ArrayList(ingredients);
            // Often could do:
            // return Collections.immutableList(ingredients);
        }
    }
    

提交回复
热议问题