سؤال

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