Вопрос

I have two functions that do nearly the same thing, the only difference is that one instantiates one of its variables while the other takes it as a parameter:

void f1()
{
    myType o;
    // do work on o
}

void f2(shared_ptr<myType> o)
{
    // do work on o
}

This is because some callers need o after the work is done, while some others do not. There is a lot of work done, and right now keeping the functions in sync is a copy-paste affair (also changing "o." to "o->"). Is it possible to combine these into a single function, such that if the caller passes in an o, then that is used (as in f2), otherwise one is constructed (as in f1)? Perhaps by setting a default value in the signature?

Это было полезно?

Решение

Use the std::make_shared function in conjunction with a default parameter :

void f2 (shared_ptr<myType> o = make_shared<myType>())

Другие советы

The first function can forward to the second function by using a std::shared_ptr with a null deleter:

struct null_deleter
{
    template <typename T>
    void operator()(T*) { }
};

void f1()
{
    myType o;
    f2(std::shared_ptr<myType>(&o, null_deleter{}));
}

Simply overload the functions:

void f1() // void seems odd, wouldn't you return o after you've done work on it?
{
    yourType o;
    // do work on o
}
void f1(yourType& o)
{
    // do work on o
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top