program tip

C ++에서 "int & foo ()"는 무엇을 의미합니까?

radiobox 2020. 7. 26. 12:50
반응형

C ++에서 "int & foo ()"는 무엇을 의미합니까?


lvalues와 rvalues에 대한이 설명읽는 동안 다음 코드 줄이 나에게 붙어 있습니다.

int& foo();
foo() = 42; // OK, foo() is an lvalue

g ++로 시도했지만, 컴파일러는 "정의되지 않은 foo () 참조"라고 말합니다. 내가 추가하면

int foo()
{
  return 2;
}

int main()
{
  int& foo();
  foo() = 42;
}

잘 컴파일되지만 실행하면 세그먼테이션 오류가 발생 합니다. 그냥 라인

int& foo();

자체적으로 문제없이 컴파일되고 실행됩니다.

이 코드는 무엇을 의미합니까? 함수 호출에 값을 어떻게 할당 할 수 있으며 왜 rvalue가 아닌가?


설명은 foolvalue 참조를 valid에 반환하는 합리적인 구현이 있다고 가정 합니다 int.

이러한 구현은 다음과 같습니다.

int a = 2; //global variable, lives until program termination

int& foo() {
    return a;
} 

이제 foolvalue 참조를 리턴하므로 다음과 같이 리턴 값에 무언가를 지정할 수 있습니다.

foo() = 42;

변수에 직접 액세스하거나 다시 호출하여 확인할 수 a있는 값으로 전역 업데이트 합니다.42foo

int main() {
    foo() = 42;
    std::cout << a;     //prints 42
    std::cout << foo(); //also prints 42
}

다른 모든 답변은 함수 내에서 정적을 선언합니다. 나는 당신을 혼란스럽게 할 수 있다고 생각합니다.

int& highest(int  & i, int  & j)
{
    if (i > j)
    {
        return i;
    }
    return j;
}

int main()
{
    int a{ 3};
    int b{ 4 };
    highest(a, b) = 11;
    return 0;
}

때문에 highest()반환에 대한 참조, 당신은에 값을 할당 할 수 있습니다. 이것이 실행될 때, b11로 변경 될 것입니다. a즉, 8과 같이 초기화를 a변경하면 11로 변경 될 것입니다. 이것은 다른 예제와 달리 실제로 목적에 도움이 될 수있는 일부 코드입니다.


int& foo();

에 대한 참조를 반환하는 foo라는 함수를 선언합니다 int. 그 예제가 실패한 것은 컴파일 할 수있는 해당 기능의 정의를 제공하는 것입니다. 우리가 사용한다면

int & foo()
{
    static int bar = 0;
    return bar;
}

Now we have a function that returns a reference to bar. since bar is static it will live on after the call to the function so returning a reference to it is safe. Now if we do

foo() = 42;

What happens is we assign 42 to bar since we assign to the reference and the reference is just an alias for bar. If we call the function again like

std::cout << foo();

It would print 42 since we set bar to that above.


int &foo(); declares a function called foo() with return type int&. If you call this function without providing a body then you are likely to get an undefined reference error.

In your second attempt you provided a function int foo(). This has a different return type to the function declared by int& foo();. So you have two declarations of the same foo that don't match, which violates the One Definition Rule causing undefined behaviour (no diagnostic required).

For something that works, take out the local function declaration. They can lead to silent undefined behaviour as you have seen. Instead, only use function declarations outside of any function. Your program could look like:

int &foo()
{
    static int i = 2;
    return i;
}  

int main()
{
    ++foo();  
    std::cout << foo() << '\n';
}

int& foo(); is a function returning a reference to int. Your provided function returns int without reference.

You may do

int& foo()
{
    static int i = 42;
    return i;
}

int main()
{
    int& foo();
    foo() = 42;
}

int & foo(); means that foo() returns a reference to a variable.

Consider this code:

#include <iostream>
int k = 0;

int &foo()
{
    return k;
}

int main(int argc,char **argv)
{
    k = 4;
    foo() = 5;
    std::cout << "k=" << k << "\n";
    return 0;
}

This code prints:

$ ./a.out k=5

Because foo() returns a reference to the global variable k.

In your revised code, you are casting the returned value to a reference, which is then invalid.


In that context the & means a reference - so foo returns a reference to an int, rather than an int.

I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory where that int is.

So to summarize you're not assigning a value to a function call - you're using a function to get a reference, and then assigning the value being referenced to a new value. It's easy to think everything happens at once, but in reality the computer does everything in a precise order.

If you're wondering - the reason you're getting a segfault is because you're returning a numeric literal '2' - so it's the exact error you'd get if you were to define a const int and then try to modify its value.

If you haven't learned about pointers and dynamic memory yet then I'd recommend that first as there's a few concepts that I think are hard to understand unless you're learning them all at once.


The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".

In your example, foo is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:

int& foo()
{
    static int x;
    return x;
}

and would succeed by changing the value of x, when saying:

foo() = 10;

The function you have, foo(), is a function that returns a reference to an integer.

So let's say originally foo returned 5, and later on, in your main function, you say foo() = 10;, then prints out foo, it will print 10 instead of 5.

I hope that makes sense :)

I'm new to programming as well. It's interesting to see questions like this that makes you think! :)

참고URL : https://stackoverflow.com/questions/36477542/what-does-int-foo-mean-in-c

반응형