When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
25 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
In C++ everything is passed by value by default
so for a function like void foo(std::string str) {} the string will be copied
but sometimes you don't want to copy, you want to refer or point to an object elsewhere that already exists
that's what references / pointers are for
my thing is though why not just use the value itself?
references / pointers fundamentally serve the same purpose, the only differences are syntax and some subtle semantic differences of references
because copying can be expensive for some types, e.g. containers like strings, and sometimes you want to modify an object elsewhere
consider how this would be different passing by value or by reference
void foo(std::string str) {
str += "hi";
}
int main() {
std::string str;
foo(str);
std::cout<<str;
}
how does the expense very ig because that is the main bit that confuses me
well, suppose I have a string that has a million characters
passing by value would copy that string
that is expensive
would using a pointer/ reference not?
no, with a pointer/reference you are simply pointing to / referring to an object that exists elsewhere
you aren't making a copy of that object
this might sound really stupid but bare with me
if you point to it doesn't your memory still have to bring all that back up so it can compute or is the plane flying over my head?
It's flying over your head
okay so just calling to it doesn't bring it all back up gotcha
every variable in your program is an object, these objects live in memory
To an extent you may have to go read the "memory" you're pointing at, but these considerations are all dependent on what you actually use the pointed/referenced object for
pointers / references simply point to / refer to those objects in memory, and access those locations in memory
@loud ruin
Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.
My b for the brainrot. Just clicked on why this would be usefull.