Use data members that free resources when they are destroyed (aka RAII).
For instance:
struct TwoStrings { std::string string1; std::string string2; TwoStrings(const std::string &input) : string1(input) { if (!input[1] == ':') { throw std::logic_error('not a Windows absolute path'); // yes, absolute paths can begin \\, this is a toy example } if (input.back() == '\\') { string2 = input; } else { string2 = input + "\\"; } } };
If the constructor throws (either logic_error or bad_alloc ), then the already initialized data element string1 destroyed, freeing the resource. In this case, string2 also destroyed, but if the constructor throws, then string2 should be empty, so it has no special effect.
string is an example of a class that manages resources, but there are many others. The most flexible of them are called "smart pointers" and can be configured to control almost any resource, and not just with self-distributed arrays of characters such as string .
source share