I’m trying to create a wrapper for int* in C++. Currently, it’s not going very well.
For the sake of testing, I’ve included 2 very taboo lines at the start, please ignore them.
#include <bits/stdc++.h>
using namespace std;
class Number {
public:
int32_t* value_32;
Number(int32_t value) {
value_32 = &value;
}
};
int main() {
int32_t v = 13;
Number* n = new Number(v);
cout << *(n->value_32) << "\n";
}
I would expect this code yields an output of 13, but it gives a random large number, ex: 1833022464. Why is this the case?
Note: changing int32_t to int yields the same problem
>Solution :
You’re taking the address of a temporary. The lifetime of value ends, and value_32 is left pointing to invalid memory. Dereferencing it invokes undefined behavior. Seeing a different number than you expect is one outcome. The number you expected is another valid outcome. Or your program crashing.
Now, you could pass a reference to an int, but even there you have to worry about lifetime issues.
class Number {
public:
int32_t* value_32;
Number(int32_t &value) : value_32(&value) { }
};
Raw pointers in modern C++ are rarely necessary, so you’d really want to ask yourself why you’re writing code like this, and whether there’s a better way to accomplish your goal.
I would also suggest you read: