The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#ifndef TRACEDCOLL_HPP
#define TRACEDCOLL_HPP
#include <iostream>
#include <vector>
#include <print>
template<typename ValT>
class TracedColl {
private:
std::vector<ValT> values;
public:
TracedColl ()
: values{} {
std::println("** CONSTRUCT {}", values);
}
TracedColl (const auto&... vals)
: values{vals...} {
std::println("** CONSTRUCT {}", values);
}
friend std::ostream& operator<< (std::ostream& os, const TracedColl& c) {
std::println(os, "{}\n", c.values);
return os;
}
auto begin() { return values.begin(); }
auto begin() const { return values.begin(); }
auto end() { return values.end(); }
auto end() const { return values.end(); }
// tracing copy/move and destructor:
TracedColl(const TracedColl& c)
: values{c.values} {
std::println("** COPY-CONSTRUCT {}", values);
}
TracedColl(TracedColl&& c)
: values{std::move(c.values)} {
std::println("** MOVE-CONSTRUCT {}", values);
}
TracedColl& operator=(const TracedColl& c) {
std::println("** COPY-ASSIGN {} to {}", c.values, values);
values = c.values;
}
TracedColl& operator=(TracedColl&& c) {
std::println("** MOVE-ASSIGN {} to {}", c.values, values);
values = std::move(c.values);
}
~TracedColl() { // tracing destructor
std::println("** DESTRUCT {}", values);
}
};
#endif // TRACEDCOLL_HPP