A comparison of Ruby pass by reference and C++ pass by reference
12 April 2010
Take the following Ruby and C++ applications:
def do_something(text)
text = "bar"
end
text = "foo"
do_something(text)
puts text
The Ruby program above outputs "foo"
- Variable "text" holds address of String object containing "foo"
- Call do_something function passing in address of String object containing "foo"
- Address of String object containing "foo" gets copied to local variable "text"
- Local variable "text" then gets the address of newly created String object "bar"
- Local variable "text" goes out of scope
- Variable "text" still holds the address of String object "foo"
#include <iostream>
using namespace std;
void DoSomething (std::string &text)
{
text = "bar";
}
int main ()
{
std::string text = "foo";
DoSomething(text);
cout << text << "\n";
return 0
}
The C++ program above outputs "bar"
- Variable "text" holds String object containing "foo"
- Call do_something function passing in address of String object containing "foo"
- Address of String object containing "foo" gets copied to local variable "text"
- String object "foo" is replaced with String object "bar"
- Local variable "text" goes out of scope
- Variable "text" holds String object containing "bar"
vexer
I would say that Ruby references were more similar to C++ pointers than they were to C++ references.
shiningththrough
I would agree with you.
billige autoversicherung
I had been arguing with my close friend on this issue for quite a while, base on your ideas prove that I am right, let me show him your webpage then I am sure it must make him buy me a drink, lol, thanks. - Kris
Cheap Car Hire Alicante Airport
Hey, I am checking this blog using the phone and this appears to be kind of odd. Thought you'd wish to know. This is a great write-up nevertheless, did not mess that up. - David
login facebook
Nice post about A comparison of Ruby pass by reference and C++ pass by reference - shiningthrough. I am very impressed with the time and effort you have put into writing this story. I will give you a link on my social media blog. All the best!