문제

while solving a test on http://cppquiz.org I found this interesting piece of code :

#include <iostream>

int f(int& a, int& b) {
    a = 3;
    b = 4;
    return a + b;
}

int main () {
    int a = 1;
    int b = 2;
    int c = f(a, a);// note a,a
    std::cout << a << b << c;
}

My question is this program legal C++ or it isnt? Im concerned about strict aliasing.

도움이 되었습니까?

해결책

You mention strict aliasing – but strict aliasing is concerned with aliases of different types. It doesn’t apply here.

There’s no rule that forbids this code. It’s the moral equivalent of the following code:

int x = 42;
int& y = x;
int& z = x;

Or, more relevantly, it’s equivalent to having several child nodes refer to the same parent node in a tree data structure.

다른 팁

Yes, it is legal.

I could formally prove it only by quoting the majority of the C++ standard text.

You are passing two references, both of which happen to refer to the same object, which is perfectly fine. You then assign new values to that single object, in turn. Also fine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top