Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the intention of ODR?

I do understand what ODR says, but I don't understand what it tries to achieve.

I see two consequences of violating it - user will get syntax error, which is totally fine. And also there may be some fatal errors, and again the user would be the only one who's guilty.

As example of violating ODR and getting some fatal error I imagine like this:

a.cpp

struct A
{
        int a;
        double b;
};
void f(A a)
{
        std::cout << a.a << " " << a.b << std::endl;
}

main.cpp

struct A
{
        int a;
        int b;

};
void f(A a);

int main()
{

        A a = {5, 6};
        f(a);

        return 0;
}

Please correct me if example isn't related to ODR.

So, is ODR trying to prohibit the user from doing such harmful things? I don't think so.

Is it trying to set some rules for compiler writers, to avoid potential harms from violating it? Probably no, since most of compilers don't check of ODR violation.

What else?

like image 616
Mister Nobody Avatar asked Dec 25 '22 04:12

Mister Nobody


1 Answers

The ODR dictates what C++ programs are well formed. A ODR violation means your program is ill-formed, and the standard does not dictate what the program will do, if it should compile, etc. Mostly ODR violations are marked "no diagnostic required" to make the job of the compiler writer easier.

This permits the C++ compiler to make certain simplifying assumptions about the code you feed it, like that ::A is the same struct type everywhere, and not have to check at each point of use.

The compiler is free to take your code and compile it to format c:. Or anything else. It is free to detect ODR violations, and use it to prove that branch of code cannot run, and eliminate paths that lead there.

like image 96
Yakk - Adam Nevraumont Avatar answered Jan 08 '23 12:01

Yakk - Adam Nevraumont