C++: pass reference as parameter but that function doesn't accept reference as parameter

时间:2017-06-20 12:31:48

标签: c++

I have this code snippet from here. Pls have a look at the file spec.cc.

Eval parse_recursive_descent (Grammar g, SymbolString input) {
    return
        parse_recursive_descent
            (g, Stack (SymbolString {g.start}, input, Path ())) ;
}

// MAIN ////////////////////////////////////////////////////////////////////////

int main () {
    Input in = read_input (std::cin) ;
    Eval  ev = parse_recursive_descent (grammar (in), string (in)) ;
    print (make_output_string (derivations (ev), accept (ev))) ;
    return 0 ;
}

The prototype of function grammar is: Grammar& grammar (Input& in) ;. So it returns a reference.

But parse_recursive_descent doesn't have the g parameter as reference. The question is: the g in function parse_recursive_descent is a reference or a value?

3 个答案:

答案 0 :(得分:3)

It's a value, copy-constructed from the reference you pass as argument.

The general idea is that all the parameters of a function are variables (of the specified type) local to the function. When you pass an argument, it is used as the initializer to construct the corresponding parameter.

答案 1 :(得分:1)

基本的是你可以为同一类型的变量分配一个引用,如:

int i = 10;
int& j = i;
int k = j;//here j is a reference and value from j is copied to k

在这里,正如您所说,函数grammar返回类型为Grammar的引用。现在,此返回值将作为参数发送到函数parse_recursive_descent(到Grammar g)。因此,只需将Grammar类型的变量分配给g即可。

Grammar g = variable of type Grammar; //this is a value copy

因此,g只是一个值而非参考。

*复制发生在Grammar类的复制构造函数中。

答案 2 :(得分:0)

Eval parse_recursive_descent(Grammar g, SymbolString input)

gGrammar类型的。你知道,因为这就是宣言所说的。

当你调用函数时,如果传递的类型与函数期望的类型不完全匹配,编译器会生成代码以使它们匹配。所以在通话中

parse_recursive_descent(grammar(in), string(in));

编译器将grammar(in)返回的引用转换为Grammar类型的对象,并将其传递给parse_recursive_descent。为了使对象为Grammar类型的对象留出空间并使用复制构造函数,传递grammar(in)返回的引用。你可以做类似的事情:

Grammar temp(grammar(in));
parse_recursive_descent(temp, string(in));

如果你这样做的唯一区别是你将有一个命名对象temp)而不是编译器在你的实际代码中创建的(未命名的)临时对象