lundi 7 juin 2021

C++: ODR violation for member functions defined outside of class body but enclosed within header guard (as shown in YouCompleteMe plugin)

I have a simple class as shown below.

  #ifndef PERSON_H
  #define PERSON_H

  #include <iostream>
  #include <string>
  using namespace std;

  struct Person {
      string name;
      string address;
      auto get_name() const -> string;
  };

 string Person::get_name() const {  // Function 'get_name' defined in a header file; function definitions in header files can lead to ODR violations
          return this -> name;
  }

  #endif

Question:
Even though the Person::get_name() function is defined outside of the struct Person, this function is defined inside the header guard PERSON_H. YouCompleteMe tool (presume using g++), it states it violates ODR. Why would it violates ODR? This function will never be defined more than once since it's control by header guard PERSON_H. I am not sure if there is a bug in the YouCompleteMe tool because i noticed i don't get the same warning message using visual studio.

Any help would be great.
Thanks.

Aucun commentaire:

Enregistrer un commentaire