tags:

views:

89

answers:

4

Am I causing a memory leak here or is it OK to do like this? Should I use a smart pointer member instead of a reference?

class A
{
public:

   A() : b_(*(new B))
   {}

private:
   B& b_;
};

int main()
{
    A a;
    return 0;
}
A: 

The language allows this, however, as you have it written, there is a memory leak. You have a new, but no corresponding delete - you need to write a destructor here, something like:

A::~A() {
    delete &b_;
}

Now, while this is legal, it is weird. A pointer will do just as well, and will probably convey better what's going on. A smart pointer would have saved you from a leak, and may be applicable.

Thanatos
And remember: if you have a non-trivial destructor, you nearly always need to sort out the copy constructor and copy assignment.
Mike Seymour
Then again... don't. If you want to manage dynamically allocated memory, make it explicit: use pointers. If you want to make it right, make those smart pointers. Hiding dynamically allocated memory behind a reference will just make it more complex to reason about the code when you or someone else has to work on it later.
David Rodríguez - dribeas
@David: That is a better worded explanation of what I meant by "a pointer will ... convey better what's going on."
Thanatos
Thank you guys for all helpful advice. My conclusion is to use a const smart pointer instead of a reference.Class A is my first attempt to make a DI containter flexible for various build configurations (I've seen a poor man's container should be avoided but I'm trying to get started with dependency injection), any advice/example on how to implement a poor man's container?
+4  A: 

You certainly are leaking memory; every new needs to be matched with a delete.

Unless there's a good reason for dynamically allocating it, you'd be better off just making b_ an object. Otherwise, use a smart pointer as you suggest, or (not recommended) delete it in your destructor, remembering to make the copy constructor and copy assignment behave correctly. In the last case, it's valid (but a bit unusual) for it to be a reference rather than a pointer.

The decision really comes down to how you want the class to behave when you copy it. In the first case, it will copy the entire object; in the second, it will behave as defined by the smart pointer; in the third, it will behave as defined by the copy constructor/assignment that you implement.

Mike Seymour
+1 for the last paragraph :)
Justin Ardini
+1  A: 

Yes, it is allowed in C++.

Of course, it is more safe to use smart pointers.

Then You shouldn't worry about clearing allocated memory in destructor.

Like this:

#include <memory>

class A {
public:
   A() : p_b( new B() )
   {}
   someMethod() {
       return p_b->something();
   }
private:
   std::auto_ptr<B> p_b;
};
int main()
{
    A a;
    return 0;
}
Pavel Chernov
I have edited the answer to use syntax highlighting --select the block of code, then press in the small button `010...`. I have also made it more compact to make the best out of the screen real state. (I have just seen that I forgot to correct the `return` statement of `someMethod`... add a type there :)
David Rodríguez - dribeas
`auto_ptr` won't behave quite the way you'd expect here - which bring us back to Mike's point about copy c-tors and assignment operators. Alternatively, you could use a `boost::shared_ptr`. All (`boost::shared_ptr`, this example, writing a copy c-tor that copies the object) behave differently, so you need to evaluate the situation to see which is right.
Thanatos
A: 

The only thing I would add to what has been said, is that even though you are allocating memory in the constructor which means that b will always start with a value, in the destructor I would change slightly what Justin wrote. I always check for NULL before I call delete and then set the pointer to NULL after I free it. In the destructor setting the pointer to NULL is kind of pointless, but is there just for consistency.

class A
{
public:

   A():b_(new B)
   ~A() { if (b) { delete b; b = NULL; } }
   {}

private:
   B* b_;

}
linuxuser27
`delete NULL;` is a valid statement in C++: it does absolutely nothing.
Thanatos
I'd suggest you break that habit; checking for null, and setting to null, simply bloat the code for no purpose. And, once again, if you write a destructor you nearly always need to fix the copy semantics.
Mike Seymour
Good suggestion. Old habits die hard, but I will keep that in mind along with Thanatos's comment. Thanks.
linuxuser27
Your class is buggy: you have forgotten to redefine the copy constructor and assignment operator as well than (in C++0x) the move constructor and move assignment operator. Lesson one of memory management: `delete` is a code smell, pick up a smart pointer.
Matthieu M.