@@ -299,6 +299,27 @@ std::ostream& operator<<(std::ostream& os, const Variant& v) {
299
299
300
300
namespace {
301
301
302
+ std::vector<std::string> ArgcArgvToVector (int argc, char * argv[]) {
303
+ std::vector<std::string> args_vector;
304
+ for (int i = 0 ; i < argc; ++i) {
305
+ args_vector.push_back (argv[i]);
306
+ }
307
+ return args_vector;
308
+ }
309
+
310
+ char ** VectorToArgcArgv (const std::vector<std::string>& args_vector,
311
+ int * argc) {
312
+ char ** argv = new char *[args_vector.size ()];
313
+ for (int i = 0 ; i < args_vector.size (); ++i) {
314
+ const char * arg = args_vector[i].c_str ();
315
+ char * arg_copy = new char [std::strlen (arg) + 1 ];
316
+ std::strcpy (arg_copy, arg);
317
+ argv[i] = arg_copy;
318
+ }
319
+ *argc = static_cast <int >(args_vector.size ());
320
+ return argv;
321
+ }
322
+
302
323
/* *
303
324
* Makes changes to argc and argv before passing them to `InitGoogleTest`.
304
325
*
@@ -320,28 +341,22 @@ namespace {
320
341
char ** EditMainArgsForGoogleTest (int * argc, char * argv[]) {
321
342
// Put the args into a vector of strings because modifying string objects in
322
343
// a vector is far easier than modifying a char** array.
323
- std::vector<std::string> args_vector;
324
- for (int i = 0 ; i < *argc; ++i) {
325
- args_vector.push_back (argv[i]);
326
- }
344
+ const std::vector<std::string> original_args = ArgcArgvToVector (*argc, argv);
345
+ std::vector<std::string> modified_args (original_args);
327
346
328
- // This is where you can add elements to the `args_vector ` vector that will be
329
- // specified to googletest.
330
- // e.g. args_vector .push_back("--gtest_list_tests ");
347
+ // Add elements to the `modified_args ` vector to specify to googletest.
348
+ // e.g. modified_args.push_back("--gtest_list_tests");
349
+ // e.g. modified_args .push_back("--gtest_filter=MyTestFixture.MyTest ");
331
350
332
- // Write the elements of the vector back into argv and modify argc.
333
- // The memory leaks produced below are acceptable because they would last the
334
- // entire lifetime of the application anyways.
335
- char ** new_argv = new char *[args_vector.size ()];
336
- for (int i = 0 ; i < args_vector.size (); ++i) {
337
- const char * arg = args_vector[i].c_str ();
338
- char * arg_copy = new char [std::strlen (arg) + 1 ];
339
- std::strcpy (arg_copy, arg);
340
- new_argv[i] = arg_copy;
351
+ // Avoid the memory leaks documented below if there were no arg changes.
352
+ if (modified_args == original_args) {
353
+ return argv;
341
354
}
342
355
343
- *argc = static_cast <int >(args_vector.size ());
344
- return new_argv;
356
+ // Create a new `argv` with the elements from the `modified_args` vector and
357
+ // write the new count back to `argc`. The memory leaks produced by
358
+ // `VectorToArgcArgv` acceptable because they last for the entire application.
359
+ return VectorToArgcArgv (modified_args, argc);
345
360
}
346
361
347
362
} // namespace
0 commit comments