Pointer vs. Reference

后端 未结 12 1648
闹比i
闹比i 2020-11-22 11:13

What would be better practice when giving a function the original variable to work with:

unsigned long x = 4;

void func1(unsigned long& val) {
     val          


        
12条回答
  •  旧巷少年郎
    2020-11-22 11:29

    If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.

    A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.

    // Sample method using optional as input parameter
    void PrintOptional(const boost::optional& optional_str)
    {
        if (optional_str)
        {
           cout << *optional_str << std::endl;
        }
        else
        {
           cout << "(no string)" << std::endl;
        }
    }
    
    // Sample method using optional as return value
    boost::optional ReturnOptional(bool return_nothing)
    {
        if (return_nothing)
        {
           return boost::optional();
        }
    
        return boost::optional(42);
    }
    

提交回复
热议问题