I have a class called Bucket that basically holds a pointer to some data and some flags. Using the function below, one can set the pointer to the data (or so I'm hoping).
template <typename T>
void Bucket<T>::setData(T datum) {
m_data = &datum;
...
}
I'm wondering what gets stored in m_data and what happens to it after the function gets popped off the call stack. My suspicion is that once datum falls out of scope, the reference is effectively useless. If that's the case, would it be better to dynamically allocate the data passed to setData and track it with m_data?
Your suspicion is correct. When you call the function, the value that you passed to the function is stored in an local variable (the function argument variable in this case) that is created on the stack for that function. You are using the pointer to store the address of that local variable, and the local variable will effectively disappear once the function is completed. Using the pointer to retrieve the value at that memory location after the function is completed is undefined.
You can store the passed value using a pointer in a few ways including: