I am currently working through the C++ Crash Course book (https://ccc.codes/) and facing the following issue in the code on Page 295 (Listing 10-17 Unit Testing for Brake events). The following code uses assertion to assert that the BrakeCommand is published but seems to throw a segmentation fault when run.
#include <iostream>
#include <stdexcept>
...
struct BrakeCommand {
double time_to_collision_s;
};
template<typename T>
struct AutoBrake {
AutoBrake(const T &publish) : publish{publish}, speed_mps{}, collision_threshold_s{5} {}
...
void observe(const CarDetected &cd) {
const auto relative_velocity_mps = speed_mps - cd.velocity_mps;
const auto time_to_collision_s = cd.distance_m / relative_velocity_mps;
if (time_to_collision_s > 0 && time_to_collision_s <= collision_threshold_s) {
publish(BrakeCommand{time_to_collision_s});
}
}
...
private:
const T &publish;
double collision_threshold_s;
double speed_mps;
};
...
void alert_when_imminent() {
int brake_commands_published{};
AutoBrake autoBrake{
[&](const BrakeCommand &) {
brake_commands_published++;
}
};
...
autoBrake.observe(CarDetected{100L, 0L});
assert_that(brake_commands_published == 1, "brake commands published not one");
}
//Run Test
void run_test(void(*unit_test)(), const char *name) {
try {
unit_test();
printf("[+] Test %s successful.\n", name);
}
catch (const std::exception &e) {
printf("[-] Test failure in %s. %s.\n", name, e.what());
}
}
int main() {
run_test(alert_when_imminent, "alert when imminent");
}
It seems that referencing brake_commands_published
from the publish
call in Autobrake::observe
seems to push the value of brake_commands_published
out of scope and causes a dangling reference error. Can anyone help me understand why this happens and how to fix it?