A virtual member function is used if it is not pure?

前端 未结 5 2142
长情又很酷
长情又很酷 2021-02-15 12:03

C++03 3.2.2 ...An object or non-overloaded function is used if its name appears in a potentially-evaluated expression. A virtual member function is used

5条回答
  •  逝去的感伤
    2021-02-15 12:19

    As @Charles Bailey pointed out, your A::f is in fact used even though it's pure virtual. But that's beside the main point.

    It's not accurate that the One Definition Rule does not apply to functions that are not used. We have:

    3.2p1 No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template.

    3.2p3 Every program shall contain exactly one definition of every non-inline function or object that is used in that program; no diagnostic required.

    Together, these requirements seem to imply that a used function must have exactly one definition, and an unused function (including a pure virtual function which is never explicitly called) may have either no definition or a single definition. In either case, multiple definitions for a non-inline function makes the program ill-formed.

    At least, I'm quite certain that's the intent. But you may be on to a hole in the phrasing, since a very literal reading does not say anywhere that multiple different definitions of the same unused function in different translation units is ill-formed.

    // x.cpp
    void f() {}
    void g() {}
    
    // y.cpp
    #include 
    void f() {
      std::cout << "Huh" << std::endl;
    }
    void h() {}
    
    // z.cpp
    void g();
    void h();
    int main() { 
      g();
      h();
      return 0;
    }
    

提交回复
热议问题