Nick
Nick

Reputation: 10539

Is there any issues with this factory pattern implementation

Recently I asked following question:

Best method to implement an abstract factory pattern

My future research show that you can implement the factory like this:

#include <stdio.h>

#include <memory>

class Base{
    char x[20000];
};

class Child : public Base{
public:
    Child(int a, int b){

    }
};

std::unique_ptr<Base> factory(){
    return std::unique_ptr<Base> { new Child(5, 6) };
}

int main(){
    Base & a = *factory();

    return 0;
}

This compiles without warnings, and it make no memory leak, even std::unique_ptr is dereferenced immediately.

Is this Base & a = *factory(); legitimate and well accepted way to "collect" value from factory?

The only problem I see here would be if a variable leave the scope. Is there something I am missing here?

Upvotes: 1

Views: 53

Answers (1)

Quentin
Quentin

Reputation: 63124

Base &a = *factory();

You dereferenced the unique_ptr and kept the reference to its pointee.
But you didn't store the unique_ptr itself.
Thus it dies at the end of the statement, taking its pointee with it, and your reference is now dangling.

Upvotes: 3

Related Questions