Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boost::ref to indicate intention in coding conventions

When functions take non-const refs as arguments, it can create hard-to-read code because at the calling site it is not obvious which inputs might be changed. This has lead some code conventions to enforce that pointers be used instead, for example

void func(int input, int* output);

int input = 1, output = 0;
func(input, &output);

instead of

void func(int input, int& output);

int input = 1, output = 0;
func(input, output);

Personally, I hate using pointers because of the need to check for null. This has lead me to wonder if boost::ref (or std::ref for C++11) can be used to signal intention, as follows:

void func(int input, int& output);

int input = 1, output = 0;
func(input, boost::ref(output));

This would be used as a company coding convention. My question is, are there any reasons why this would not be a good idea?

like image 432
user1487088 Avatar asked Jun 22 '26 01:06

user1487088


1 Answers

It's not a bad idea, but it's not really enforced (as PiotrNycz notes). It's effectively just a comment.

We can do better though:

template <typename T>
class output_argument
{
public:
    template <typename U>
    friend output_argument<U> out(U& ref);

    T& get() const
    {
        return mRef;
    }

    operator T&() const
    {
        return get();
    }

private:
    explicit output_argument(T& ref) :
    mRef(ref)
    {}

    output_argument& operator=(const output_argument&); // not defined

    T& mRef;
};

template <typename U>
output_argument<U> out(U& ref)
{
    return output_argument<U>(ref);
}

Giving:

void foo(int x, output_argument<float> f)
{
    int i = static_cast<int>(f);

    f.get() = static_cast<float>(i + x);
}

int main()
{
    float f = 5.0f;

    //fails: foo(1, f);
    foo(1, out(f));
}

But generally these kinds of utilities are not necessary, because the function name should convey what's happening to the arguments: swap(x, y) quite clearly modifies the arguments! And returning values should be done with a return type, further limiting the cases this utility can be used.

like image 168
GManNickG Avatar answered Jun 23 '26 17:06

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!