MCPcopy Create free account
hub / github.com/davisking/dlib / test_composition

Function test_composition

dlib/test/scope.cpp:110–147  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

108 };
109
110 void test_composition()
111 {
112 int counter{0};
113
114 const auto fn = [&]
115 {
116 // Pretend you're in a cpp file using a C library which isn't exposed to the API via the header.
117 // You want to return some results, but those results are only valid so long as something returned by the C library is still alive
118 // You want to delay releasing any resources allocated by the C library until after you've returned your results and the caller is done using them.
119 // You could return a std::unique_ptr<results> object with a custom deleter which deletes that resource but because all types in std::unique_ptr
120 // must be complete types, you would have to pollute the header. You can use std::shared_ptr with a custom deleter, defined at runtime,
121 // but this is less efficient.
122 // You can use a scope_exit_erased object to wrap the resouce management function from the C library and delay the call further up the stack,
123 // all behind a type erased callback.
124
125 // pretend malloc() is a fancy function from some exotic C library.
126 // pretend free() is another fancy function which you don't want users to have to manually call, and you want to delay calling it until after the results are used
127 // pretend cstdlib is a fancy header you don't want to expose in your own header file.
128 char* data = (char*)std::malloc(100);
129 std::memset(data, 0, 100);
130 std::snprintf(data, 100, "hello there!");
131 scope_exit_erased s{[=, &counter] {free(data); ++counter;}};
132
133 results_with_delayed_C_library_resource_management results{100, data, std::move(s)};
134
135 return results;
136 };
137
138 {
139 // Oh, look at me. I'm using these results, blissfully unaware that some super complicated function in a C library will get called when i'm done using results.
140 const auto results = fn();
141 DLIB_TEST(results.ndata == 100);
142 DLIB_TEST(std::strcmp(results.data, "hello there!") == 0);
143 DLIB_TEST(counter == 0);
144 }
145
146 DLIB_TEST(counter == 1);
147 }
148
149// ---------------------------------------------------------------------------------------------------
150

Callers 1

perform_testMethod · 0.85

Calls 1

moveFunction · 0.85

Tested by

no test coverage detected