Factory method pattern implementation in C++: scoping, and pointer versus reference


Question

I've been looking at the example C++ Factory method pattern at Wikipedia and have a couple of questions:

  1. Since the factory method is static, does that mean the newly created object won't go out of scope and have the destructor method called when the factory method exits?

  2. Why return a pointer, as opposed to a reference? Is it strictly a matter of preference, or is the some important reason for this?

edit: The more I think about it, both the reference and the pointer returned will stay in scope because they are referenced outside of the method. Therefore, the destructor won't be called on either one. So it's a matter of preference. No?

edit2: I printed out the destructor call on the returned reference, and it doesn't print until the program exits. So, barring further feedback, I'm going to go with the reference for now. Just so I can use the "." operator on the returned object.

1
1
11/28/2012 6:19:56 PM

I'm thinking there is a greater issue of understanding memory management. The factory method is allocating items on the heap (using new). Items on the heap never get automatically reclaimed (except by modern desktop OSs on process termination). The behavior you are describing is for items on the stack where they are reclaimed when you leave the local scope.

7
3/30/2009 3:06:12 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon