Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The safety of returning a new pointer as a reference: MyClass& () { re 1

Status
Not open for further replies.

Ahnfelt

Programmer
Joined
May 29, 2004
Messages
2
Location
DK
My question is simply, will this lead to memory leaks with any otherwise perfect class) or does the compiler know when the newly created variable (created with new but returned as a reference (not a pointer)) will go out of scope? Thanks a lot - Joakim.

Code:
#include <iostream>

class Foo
{
public:
  Foo(bool blah) { foo = blah; std::cout << "init" << foo << std::endl; }
  ~Foo() { std::cout << "exit" << foo << std::endl; }
  bool foo;
};

Foo& test() { return *new Foo(false); }

int main()
{
  Foo a(true);
  a = test();
}

/*
  output: (1 is for a true value and 0 is for a false value)
    init1
    init0
    exit0
*/
 
>will this lead to memory leaks

Yes

>does the compiler know when the newly created variable...will go out of scope

No

Code:
Foo& test() { return *new Foo(false); }
Returns a new Foo by reference.

Code:
a = test();
Assigns a (using the assignment operator) the values of the new:ed Foo. It doesn't transfer ownership of the pointer/reference.

a will be destructed properly then it goes out of scope. But not the new:ed (which is a whole other instance).

Rule of thumb: For every new you must have a delete. Note that you could "hide" and automate the delete by using a std::auto_ptr.

Code:
  #include <memory>
  ..
  {
    std::auto_ptr<Foo> foo = new Foo(true);
    ...
    // foo will be deleted when it goes out of scope.
  }
Also, if new fails (as it may do), you should make sure that test() throws an exception as you're not allowed to assign NULL to a reference.

/Per

&quot;It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure.&quot;
 
Thanks for the quick response :)
I figured it would happen as there was an uneven number of contructions and destructions (see the output: comment), but I had to make sure. I will return a pointer as usual instead :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top