ex10 due Wednesday
ex11 due next Monday (not this Friday)
midterm review Thursday
midterm exam Friday, here
paper readings: too difficult? too boring? too long? too many unfamiliar terms?
clang-format -style Google -i
// bad input
# include <iostream>
int main()
{ std::cout << "hello world\n"; return 0; }
// bad input
#include <iostream>
int main() {
std::cout << "hello world\n";
return 0;
}
export GCC_COLORS=1
run it in bash
or add it to your bash profile
gcc 4.9+ will then show colored warnings/errors
destructor
copy constructor
copy assignment operator
(next week: rule of zero)
start from lec 4: vector v0, goal: vector.cc
#include <iostream>
typedef int T;
struct vector {
size_t size;
T *data;
};
int main(void) {
size_t n = 10;
vector v;
v.size = n;
std::cout << v.size << std::endl;
std::cout << v.data << std::endl;
}
initial value of v
? default constructor (value undefined)
change struct
to class
add constructor (new T[n] with initial_value) & size() & data()
default arguments
operator overloading []
explicit vs implicit constructor
initialization lists
range-based loop: define begin()
& end()
without destructor, valgrind reports memory leaks
delete
vs delete[]
- valgrind again
without copy constructor: double free
be careful: shallow vs deep copy
explicit vs implicit
disable compiler-generated functions using = delete;
without copy constructor: leak & double free
be careful again: shallow vs deep copy
self assignment
vector v0; // default constructor
vector v0a = 10; // constructor (implicit)
vector v0b(10); // constructor (explicit)
vector v1 = v0; // copy constructor (implicit)
vector v2(v0); // copy constructor (explicit)
vector v3;
v3 = v0; // copy assignment operator
if you define one of
you probably should define all three of them!
reason: the compiler-generated version won’t work
vector foo(size_t n) {
vector v(n);
return v;
}
vector new_v(v);
return vector
from a function?
copy constructor is heavy-weight
return a reference? lifetime problem.
use a reference to hold the value? compile error.
return value optimization (RVO): try -fno-elide-constructors
rule of five: move constructor & move assignment operator
modify your 3D Point class from lec 9 exercise 1
disable the copy constructor and copy assignment operator
attempt to use copy & assign in code, and see what error the compiler generates
write a CopyFrom()
member function, and try using it instead
write a C++ class that:
is given the name of a file as a constructor argument
has a “GetNextWord()” method that returns the next whitespace or newline-separate word from the file as a copy of a “string” object, or an empty string once you hit EOF.
has a destructor that cleans up anything that needs cleaning up
Write a C++ function that:
uses new
to dynamically allocate an array of strings
uses delete[]
to free it
delete
to delete each allocated stringdelete[]
to delete the string pointer arrayC++ object model; virtual
revisited