Simulate Java by C++ with reference

Can we just use reference in C++ when I dont need change location of pointer? The purpose is to simulate process of Java. For example:
//declare an object
Foo *f = new Foo;
Foo &rf = *f;

//pass parameter
void foo(Foo &f){}
foo(rf);

I want to avoid using class variable created in stack.

Thanks!
This works just as well: foo(*f);

Or, for that matter:
1
2
Foo f;
foo(f);

That passes by reference, thus not making a copy of the object.
You can't program C++ as if it was Java.

I want to avoid using class variable created in stack.

Why? Using automatic storage duration whenever possible is the best way to do it because it makes your code more clean and you don't have to remember deleting the object.

1
2
3
4
5
6
//declare an object
Foo f;

//pass parameter
void foo(Foo &f){}
foo(f);
Last edited on
Using raw pointers and allocating on the heap will be a disaster since C++ has no garbage collection.

If you use smart pointers (e.g. boost::shared_ptr ) then things become a lot more similar to Java.

boost::shared_ptr<Foo> myref(new Foo);

now pass around myref like it was a java reference and it automagically frees memory when there are no more instances pointing to it.
But sometime I need process a large image considering the small memory space of stack. So, I think I have to allocate the object of image in heap
But what if I can free the memory by codes like "delete" in C++ and leave a dangling reference. Can I use C++ as JAVA?
Last edited on
std::string, std::vector and many other containers use dynamic allocations internally so they will not take up much space on the stack. An image class will work the same way. If you try to make an image class without dynamically allocating the pixel data you would have to store a large fixed size array in the object which is not so good because images often have various sizes.
Last edited on
Topic archived. No new replies allowed.