Setting the value of a variable

Hi,

I was wondering if Foo bar = *(new Foo()) is okay to do, or am I wasting memory because I cannot delete the the data from the heap after assigning the value to bar.

Thanks
or am I wasting memory because I cannot delete the the data from the heap after assigning the value to bar.
That's exactly the problem.

You can write it like so:
1
2
3
Foo bar;
Foo bar();
Foo bar = Foo();
Foo bar()
Classical mistake. This line doesn't define an object of type Foo by calling its default constructor. It declares a function that takes no parameters and returns a Foo.
Hi,

I think writing
Foo& bar = *(new Foo());
will do the job. I guess you are trying to achieve the motive that you can use a dynamically allocated variable similar to a normal variable and yes reference variable allows you to do just that.
I used the above notation quite a few times.
To delete the memory you must write:
delete &bar;
That doesn't work.
That doesn't work.

Why?
Oops. Never mind. I missed the ampersand.

I have to say, though: that's very poor style.
You're defining a pointer that's owned locally but which syntactically doesn't look like a pointer. The fact that different syntax is used to deal with pointers than with objects is what constantly reminds C++ programmers that the thing they're using needs to be freed. If you get rid of that reminder you're just making the difficult job of memory management even more error-prone.
The delete & bit doesn't help things in the least, either. It just looks utterly wrong.
Topic archived. No new replies allowed.