#References and Pointers

25 messages · Page 1 of 1 (latest)

strange quartzBOT
#

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.

full zinc
#

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

loud ruin
#

my thing is though why not just use the value itself?

full zinc
#

references / pointers fundamentally serve the same purpose, the only differences are syntax and some subtle semantic differences of references

full zinc
#

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;
}
loud ruin
#

how does the expense very ig because that is the main bit that confuses me

full zinc
#

passing by value would copy that string

#

that is expensive

loud ruin
#

would using a pointer/ reference not?

full zinc
#

you aren't making a copy of that object

loud ruin
#

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?

dusty bramble
#

It's flying over your head

loud ruin
#

okay so just calling to it doesn't bring it all back up gotcha

full zinc
dusty bramble
#

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

full zinc
#

pointers / references simply point to / refer to those objects in memory, and access those locations in memory

strange quartzBOT
#

@loud ruin

Please Do Not Delete Posts!

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.

loud ruin