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"
Comments
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.