1

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?

Justin R.
  • 23,435
  • 23
  • 108
  • 157

3 Answers3

4

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

void f2 (shared_ptr<myType> o = make_shared<myType>())
Chnossos
  • 9,971
  • 4
  • 28
  • 40
  • Could this be generalized to support parameters that require some pointer manipulation, like "f(shared_ptr& o)"? – Justin R. Mar 27 '14 at 23:13
  • For a reference to have a default parameter, you need a global variable of the same type, i.e. one `shared_ptr g = std::make_shared();` in the global scope, and then `void f (std::shared_ptr & o = g)`. What do you want to do, specifically ? – Chnossos Mar 28 '14 at 00:00
  • My concrete aim was met by your answer. I was just thinking through this, trying to wrap my head around defaults. – Justin R. Mar 28 '14 at 01:38
1

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{}));
}
nosid
  • 48,932
  • 13
  • 112
  • 139
0

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
}
smoothware
  • 898
  • 7
  • 19
  • I was hoping to have just one function, so that I don't have to duplicate code between f1 and f2 (or f1 & f1). As an aside, the work done in these functions are all side-effects. It's a very non-functional design. – Justin R. Mar 27 '14 at 21:14
  • 1
    Call second from first, put all the logic in the function with the argument. – Joanne C Mar 27 '14 at 21:14