Video Coming Soon...
60: Advanced Conversions
This is where I get into the plethora of constructors you need in modern C++ code...or just don't use them and go with simpler designated initializers until you do.
The Code
This code may need to be demonstrated more interactively to show each of the constructors used and why. Could be a really large exercise.
View Source file ex60.cpp Only
#include <fmt/core.h>
#include <chrono>
#include <thread>
#include <string>
#include <utility>
#include <ranges>
constexpr const int MAX_NAME=1024 * 10;
struct InsanePerson {
char* name;
public:
explicit InsanePerson(const char* s = "") : name(nullptr)
{
if(s) {
name = new char[MAX_NAME];
std::strcpy(name, s);
}
}
~InsanePerson() {
fmt::println("destroy runs! {:p}", name);
delete[] name;
}
// copy
InsanePerson(const InsanePerson& other)
: InsanePerson(other.name) {}
// move
InsanePerson(InsanePerson&& other) noexcept
: name(std::exchange(other.name, nullptr)) {}
// copy assign
InsanePerson& operator=(const InsanePerson& other) {
return *this = InsanePerson(other);
}
// move assign
InsanePerson& operator=(InsanePerson&& other) noexcept
{
std::swap(name, other.name);
return *this;
}
void print() {
fmt::println("I am {}.", name);
}
};
int main(int argc, char* argv[]) {
std::vector<InsanePerson> others;
std::array<InsanePerson, 20> people;
fmt::println("---- setup loop");
for(size_t i = 0; i < 10; i++) {
InsanePerson who("Test");
// trigger copy
others.push_back(who);
fmt::println("name after copy: {:p}", who.name);
// trigger move
others.emplace_back(std::move(who));
fmt::println("name after move: {:p}", who.name);
}
fmt::println("--- enumerate badness");
for(auto [i, who] : std::views::enumerate(others)) {
fmt::println("before move: {:p}", who.name);
// trigger copy assign and move assign
people[i] = who;
fmt::println("after move: {:p}", who.name);
}
fmt::println("--- print everyone");
for(auto& who : people) {
who.print();
}
fmt::println("!!!!!!!!!!! end");
}
The Breakdown
line of code- Description.
The Discussion
Blah blah.
Further Study
- https://en.cppreference.com/cpp/language/rule_of_three
- https://en.cppreference.com/cpp/language/move_assignment
- rvalue reference https://en.cppreference.com/cpp/language/reference
- forwarding reference (so different! lol) https://en.cppreference.com/cpp/utility/forward
- https://en.cppreference.com/cpp/language/value_category
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.