[英]What happens when I store a pointer to a parameter passed-by-value in C++?
I have a class called Bucket that basically holds a pointer to some data and some flags. 我有一个名为Bucket的类,该类基本上包含一些数据和标志的指针。 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. 我想知道什么存储在m_data中,以及函数从调用堆栈弹出后会发生什么。 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?
如果是这样,最好动态分配传递给setData的数据并使用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: 您可以通过几种方式使用指针存储传递的值,包括:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.