Lecture 10

Note: Careful with constructors that can take one param

struct Node {
  ...
  Node (int data):
    data{data}, next{nullptr};
}
  • single-arg constructors create implicit conversions eg. Node n{4}

  • but also Node n=4;

    • implicit concersion from int to Node

int f(Node n);
f(4); // works - 4 implicitly converted to Node

Node m{4}; // works fine
Node m = 4; // works - but 4 is not a node, it is an int 

DANGER:

  • accidentally passing an int to a function expecting a Node

    • silent conversion

    • compiler does not signal an error

    • potential errors are not caught

How to fix

  • Disable the implicit conversion - make constructor explicit

Destructors

When an object is destroyed:

  • stack-allocatd: goes out of scope

  • heap-allocated: is deleted

  • A method called the desctructor is run

  • Classes come with a destructor (just calls destructors for all fields that are objects)

What happens when an object is destroyed?

  1. destructor body runs

  2. fields' destructors are invoked in reverse declaration order (for fields that are objects)

  3. space deallocated

When do we need to write a destructor?

If np goes out of scope

  • pointer np is reclaimed (stack-allocated)

  • the list is leaked

If we say delete np;:

Write a destructor to ensure the whole list is freed:

Now - delete np; frees the whole list

  • invokes *next's destructors using recursion

  • therefore, the whole list is deallocated

Copy Assignment Operator

  • You may need to write your own copy assignment operator:

Why is this way dangerous?

When writing operator=, always watch out for self-assignment:

Better Way:

Note:

Alternative: copy-and-swap idiom

Rvalues and Rvalue references

Recall:

  • an lvalue is anything with an address

  • an lvalue ref (&) is like a const pointer with auto-deret

    • always initialized to an lvalue

Now consider:

  • compiler creates a temporary object to hold the result of plusOne

  • other is a reference to this temporary

    • copy constructor deep-copies from this tmeporary

But

Last updated

Was this helpful?