samedi 12 août 2017

When I access static const member variable in two different cpps, got "multiple definition"

I have a non-template class String(string.h):

class String {
 public:
  static const unsigned int npos;
  ...
};

And I initialize it in different cpp file(string.cpp):

const unsigned int String::npos = static_cast<unsigned int>(-1);

When I use the String in different cpps, I got multiple definition error.

I have read the code of std::string in STL. The basic_string likes that:

template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
public:
  ...
  ///  Value returned by various member functions when they fail.
  static const size_type    npos = static_cast<size_type>(-1);
  ...

And the implementation of some functions are in the basic_string.tcc, and the declaration of 'npos' also in this file:

namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

#if _GLIBCXX_USE_CXX11_ABI

  template<typename _CharT, typename _Traits, typename _Alloc>
    const typename basic_string<_CharT, _Traits, _Alloc>::size_type
    basic_string<_CharT, _Traits, _Alloc>::npos;
  ...

But when I use std::string, it will not cause any errors.

So why STL has no errors, but I do wrong there. How to correct it? Thank you.

Aucun commentaire:

Enregistrer un commentaire