Does redefining a function from the standard library violate the one-definition rule?

前端 未结 3 2018
鱼传尺愫
鱼传尺愫 2021-01-06 00:58
#include 

double log(double) {return 1.0;}
int main() {
  log(1.0);
}

Suppose the function log() in <

3条回答
  •  春和景丽
    2021-01-06 01:04

    The following addresses a previous revision of the OP. I leave it here in case future readers come here with a similar query.

    I guess that two names refer to the same entity if and only if they have the same declarative region, where the concept "declarative region" is defined in the standard [...] Is this guess correct? Is there any word in the standard supporting this?

    It's called variable hiding or shadowing colloquially. And the standard says what you said almost verbatim. §3.3.10 ¶1 in the current C++17 standard draft:

    A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class


    So does this code violate the one-definition rule (see here, since no diagnostic required, this code may compile in some compiler and we cannot assert it is correct)?

    I won't expect it to. The standard requires that all cheader headers (and in particular cmath) introduce their symbols in the std namespace. An implementation that also pours it into the global namespace is standard conforming (since the standard leaves that bit as unspecified), but I would find in bad form. You are correct that it could happen. Now if you were to include math.h (against sage advice) then that would definitely result in a violation of the one definition rule.

提交回复
热议问题