Passing optional parameter by reference in c++

后端 未结 10 1851
天涯浪人
天涯浪人 2020-12-02 22:39

I\'m having a problem with optional function parameter in C++

What I\'m trying to do is to write function with optional parameter which is passed by reference, so th

10条回答
  •  不知归路
    2020-12-02 23:05

    Here is another crazy way that does not result in memory leaks, which you should never use in real life, but seems to be standard compliant at first glance and compiles with Visual C++ 2008 & g++ 3.4.4 under Cygwin:

    void foo(double &bar, double &foobar = (*((double*)0)))
    {
       bar = 100;
       double* pfoobar = &foobar;
       if (pfoobar != 0)
           foobar = 150;
    }
    

    To reiterate: DON'T DO THIS! THERE ARE BETTER OPTIONS! OVERLOADING CAN BE YOUR FRIEND! But yeah, you can do it if you're foolish and careful. :)

提交回复
热议问题