Comming from Java I would like to implement the following “test multiple implementations” idiom in C++
void testMethod() {
List veryBigList = createNewRandomList(10000);
Algo algo = createAlgo(veryBigList);
algo.run();
}
// this can be overwritten from a subclass to test against different algo
Algo createAlgo(List list) {
Algo a(list);
return a;
}
List createNewRandomList(int size) {
List l = new ArrayList(size);
// fill list with random objects
return l;
}
I’m a bit lost how to do this the right way in C++ … when I’m doing it this way:
void test_method() {
vector<string> big_list(10000);
init_random_list(big_list);
algo my_algo = create_algo(big_list);
my_algo.run();
}
algo create_algo(vector<string> list) {
algo a(list);
return a;
}
void init_random_list(vector<string> list) {
// fill list with random objects
}
then what will C++ do? Will it copy the full list to go to create_algo and then on return it’ll copy the algo (and the list again)??
But when using call by reference I would access the reference in test_method outside of the scope of algo causing a lot trouble and violating the RAII principle, right?
I know for some implementations of C++ they optimize speed for call by value according to this doc, but can I rely on that for g++ and visual c++?
Assuming that the code is exactly as you posted, and that
algocan be modified to store a reference, then you probably want to pass and store a reference.