Pointing arguments
What if you have a pointer defined in one place and you want to assign some value in a special function? How to pass that pointer to the function and receive and
#include <iostream>
struct SimpleStruct {
int bar;
};
void foo(SimpleStruct* s) {
s = new SimpleStruct;
s->bar = 42;
}
int main(int argc, char const *argv[])
{
SimpleStruct* x = nullptr;
foo(x);
std::cout << x->bar << std::endl;
return 0;
}
C style
In C one would use a pointer for that
#include <iostream>
struct SimpleStruct {
int bar;
};
void foo(SimpleStruct** s) {
*s = new SimpleStruct;
(*s)->bar = 42;
}
int main(int argc, char const *argv[])
{
SimpleStruct* x = nullptr;
foo(&x);
std::cout << x->bar << std::endl;
delete x;
return 0;
}
By reference
But in C++ it is logical to use a reference, innit?
#include <iostream>
struct SimpleStruct {
int bar;
};
void foo(SimpleStruct* &s) {
s = new SimpleStruct;
s->bar = 42;
}
int main(int argc, char const *argv[])
{
SimpleStruct* x = nullptr;
foo(x);
std::cout << x->bar << std::endl;
delete x;
return 0;
}
C++ style
But the clean way would be to use smart pointers
#include <iostream>
#include <memory>
struct SimpleStruct {
int bar;
};
void foo(std::unique_ptr<SimpleStruct>& s) {
s = std::make_unique<SimpleStruct>();
s->bar = 42;
}
int main(int argc, char const *argv[])
{
std::unique_ptr<SimpleStruct> x;
foo(x);
std::cout << x->bar << std::endl;
return 0;
}