简体   繁体   中英

Fluent interface pattern and std::unique_ptr

I am playing with the fluent interface pattern.

First, I wrote something like that:

class C
{
public:
    C() { }

    C* inParam1(int arg1){ param1 = arg1; return this; }
    C* inParam2(int arg2){ param2 = arg2; return this; }

private:
    int param1;
    int param2;
}

Then I tried to use the std::unique_ptr, but then I realized that I do not know how to "shift" the pointer (this) along the chain. I tried something like:

return std::move(this);

that of course does not work.

How can I do this? Are there any problems doing something like this?

In order to reply to comments like: "do not use pointers": there isn't (yet) any practical reason because I am doing this with pointers, is just something I wonder if can be done this way.

Why do you have to return pointers at all?

class C
{
public:
    C create() { return C(); }

    C & inParam1(int arg1){ param1 = arg1; return *this; }
    C & inParam2(int arg2){ param2 = arg2; return *this; }

private:
    C() { }
    int param1;
    int param2;
};

I must admit I don't understand the purpose of that create function or why the constructor is private or how you actually create objects of this class at all. In my understanding, the class should actually be like this:

class C
{
public:
    C() {}

    C & inParam1(int arg1){ param1 = arg1; return *this; }
    C & inParam2(int arg2){ param2 = arg2; return *this; }

private:        
    int param1;
    int param2;
};

And used like this:

int main()
{
    C().inParam1(10).inParam2(20).whatever();
}

There can be only one std::unique_ptr instance for any given instance (because each would try to delete it and that can be done only once). Therefore, while create can return a std::unique_ptr , the other two methods cannot.

Is there any reason why you don't have the other methods return a reference rather than a pointer? And why don't you just have a public constructor? I don't see the value of the create method in this example.

You missed one important think from the c++ fluent interface example :

//it doesn't make sense to chain after create(), so don't return *this

Therefore, you shouldn't return anything from your create() method.

However if you still want to return something, at least do not (mis-)use unique_ptr , and just return a new object :

C create() { return C(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM