HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Perfect-forwarding while implementing emplace

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whileperfectforwardingimplementingemplace

Problem

I am trying to write a class similar to std::set, and I was wondering if I handled the perfect forwarding right in implementing the emplace member function below. Basically, I forwarded calls to my class to a member set. But I wasn't sure whether I used std::forward enough.

Also, is there an easy way to tell when something is not forwarded as desired, and values are copied instead?

#include 
using namespace std;

template
class myset {
  std::set m_s;
  typedef typename std::set::iterator iterator;
  int cnt;
public:
  template 
  pair  emplace ( Args&&... args ) {
    pair p = m_s.emplace(std::forward(args)...);
    if (p.second) //true if a new element was inserted
      cnt ++; //house keeping
    return p;
  }
};

int main() {myset s;}

Solution

You are using std::forward correctly. However, there are several other things worth noting about your code:

  • why do you need a private counter instead of re-using m_s.size() that will automatically update itself after each emplace_back()?



  • are you sure that you don't need additional template arguments Compare and Allocator instead of relying on their defaults std::less and std::allocator?



  • since you are using C++11 already, please use auto to get rid of the pair (and if you are using C++14, you can also use auto for the return type).



  • try also to write using iterator = typename std::set::iterator; because left-to-right is much easier to parse than right-to-left of the current typedef.

Context

StackExchange Code Review Q#57494, answer score: 6

Revisions (0)

No revisions yet.