Binding a temporary to const reference in class member leads to undefined behavior.
The class FileSystemPolicy is used to mock certain functions. It is passed to ResponseBuilder and subclasses as argument in the constructor. The class is saved as a const reference and called when needed.
The const reference becomes invalid, leading to an invalid memory usage and sometimes segfault.
The solution is to construct an object beforehand, which is passed to the constructor.
Binding a temporary to const reference in class member leads to undefined behavior.
The class FileSystemPolicy is used to mock certain functions. It is passed to ResponseBuilder and subclasses as argument in the constructor. The class is saved as a const reference and called when needed.
Binding a temporary to a const reference does extend the lifetime until the reference goes out of scope. --> https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
For easier use the constructor of ResponseBuilder and subclasses have a temporary as default argument. However binding a temporary to a const reference in a class constructor does not extend the lifetime of the temporary. --> https://stackoverflow.com/questions/2784262/does-a-const-reference-class-member-prolong-the-life-of-a-temporary
The const reference becomes invalid, leading to an invalid memory usage and sometimes segfault. The solution is to construct an object beforehand, which is passed to the constructor.
To ensure that no reference to a temporary is passed, the rvalue binding (&&) can be deleted - since C++11. --> https://stackoverflow.com/questions/12387239/is-it-idiomatic-to-store-references-members-in-a-class-and-are-there-pitfalls
Another alternative is to require a pointer instead of a reference --> (again) https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ However in that case a NULL pointer could be passed.
Solution: