Consider the below example where I create the local variable specialNumber
in main()
, and pass it by reference to a new thread, as well as another function (please disregard the lack of a lock/mutex):
#include <iostream>
#include <thread>
void threadRun(int& number) {
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << number << std::endl;
number += 1;
}
}
int main() {
int specialNumber = 5;
std::thread newThread(threadRun, std::ref(specialNumber));
otherFunction(specialNumber);
newThread.join();
}
void otherFunction(int& number) {
// does something with number
}
I am aware that passing references to local variables around should generally be avoided, as once that function terminates the variable will be out of scope and the reference will be invalid.
However, since the variable is local to main()
, and that function won't terminate until the whole program terminates, is there anything wrong with this practice?
My specific use-case would be storing a small object here (mainly consisting of pointers to heap objects along with helper functions), which would be used by multiple threads and/or functions, and passing around a reference to it. I'm aware an alternative is storing it in the heap with a smart pointer such as shared_ptr
, but storing such a small object this way seems inefficient to me.
I apologize if any of my terminology is incorrect, I am quite new to C++. Please do correct me!