在给函数使用原始变量时,更好的做法是什么:

unsigned long x = 4;

void func1(unsigned long& val) {
     val = 5;            
}
func1(x);

or:

void func2(unsigned long* val) {
     *val = 5;
}
func2(&x);

勒夫:有什么理由选择一个而不是另一个吗?


当前回答

指针

A pointer is a variable that holds a memory address. A pointer declaration consists of a base type, an *, and the variable name. A pointer can point to any number of variables in lifetime A pointer that does not currently point to a valid memory location is given the value null (Which is zero) BaseType* ptrBaseType; BaseType objBaseType; ptrBaseType = &objBaseType; The & is a unary operator that returns the memory address of its operand. Dereferencing operator (*) is used to access the value stored in the variable which pointer points to. int nVar = 7; int* ptrVar = &nVar; int nVar2 = *ptrVar;

参考

A reference (&) is like an alias to an existing variable. A reference (&) is like a constant pointer that is automatically dereferenced. It is usually used for function argument lists and function return values. A reference must be initialized when it is created. Once a reference is initialized to an object, it cannot be changed to refer to another object. You cannot have NULL references. A const reference can refer to a const int. It is done with a temporary variable with value of the const int i = 3; //integer declaration int * pi = &i; //pi points to the integer i int& ri = i; //ri is refers to integer i – creation of reference and initialization

其他回答

我的经验法则是:

如果你想对指针进行算术运算(例如,增加指针地址以遍历数组),或者如果你必须传递一个空指针,请使用指针。

否则使用引用。

考虑一下c#的out关键字。编译器要求方法的调用者将out关键字应用于任何out参数,即使它已经知道它们是否存在。这是为了提高可读性。尽管在现代ide中,我倾向于认为这是语法(或语义)突出显示的工作。

引用类似于指针,除了不需要使用前缀*来访问引用所引用的值。同样,在初始化对象之后,不能引用另一个对象。

引用对于指定函数参数特别有用。

有关更多信息,请参阅“Bjarne Stroustrup”(2014)的“c++之旅”(A Tour of c++)第11-12页

如果你要修改变量的值,你应该传递一个指针。 尽管在技术上传递引用或指针是相同的,但在用例中传递指针更具有可读性,因为它“通告”了函数将更改值的事实。

如果你有一个参数,你可能需要指出没有一个值,通常的做法是使参数为指针值并传递NULL。

在大多数情况下(从安全角度来看),更好的解决方案是使用boost::可选。这允许您通过引用传递可选值,也可以作为返回值。

// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& 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<int> ReturnOptional(bool return_nothing)
{
    if (return_nothing)
    {
       return boost::optional<int>();
    }

    return boost::optional<int>(42);
}