I'm dealing with C++ objects that use destructor to deallocate resources. When passing those objects to a function with an arbitrary number of parameters. Is there any way to get rid of using pointers in this case?
One possible solution is passing a vector of pointers to those objects. if I pass the objects themselves, the destructors will be called twice, one is the real objects, another is when the vector is deallocated.
#include<iostream>
#include<vector>
class integer {
private:
int data;
public:
integer(int value = 0): data(value) {}
~integer() {}
void increase() {
data++;
}
friend std::ostream& operator<<(std::ostream& os, const integer& x);
};
std::ostream& operator<<(std::ostream& os, const integer& x) {
os << x.data;
return os;
}
void foo(std::vector<integer*> vec) {
for (auto it = vec.begin(); it != vec.end(); it++) {
(*it)->increase();
}
}
int main() {
integer x1(3);
integer x2(4);
integer x3(5);
std::cout << x1 << " " << x2 << " " << x3 << std::endl;
foo({&x1, &x2, &x3});
std::cout << x1 << " " << x2 << " " << x3 << std::endl;
return 0;
}
Expected results:
3 4 5
4 5 6