0

Consider following piece of code:

//option no 1
struct foo{
    foo(baz &b) : _b(b){}

    std::reference_wrapper<baz> _b;
};

//option no 2
struct bar{
    bar(std::reference_wrapper<baz> b) : _b(b){}

    std::reference_wrapper<baz> _b;
};

I am wondering if there are any practical differences between initializing foo and bar. If so, what are the pros and cons of each solution and which should be preferred?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
bartop
  • 9,971
  • 1
  • 23
  • 54

1 Answers1

1

There are at least difference with types with conversion operator:

struct tobaz
{
    operator baz&() const { static baz b; return b; }
};

Then

foo{tobaz()}; // Compile
bar{tobaz()}; // Won't compile

As only one user conversion can take place.

Demo

Error would happen the other side for struct with operator std::reference_wrapper<baz>().

Jarod42
  • 203,559
  • 14
  • 181
  • 302