Search code examples
c++stldllexport

Export a class with std::string


I know this subject has been covered and re-talked, but I still get stuck every time I need to do something like that, and the internet is full of different answers. so I decided to simply ask how to deal with such situation once and for all.

Lets say I have the following class:

class PETS_EXPORT_API dog
{
public:
  dog(std::string name):_name(name){}
  ~dog(){}

private:
  std::string _name;
};

Obviously this code would generate a warning because I'm trying to export std::string. How do I solve such issue ?

thanks!


Solution

  • Alternative to Joe McGrath's answer:

    If you really want your clients to have access to Dog public & protected interface, and does not make sense to have an abstract interface,

    • You could use the pImpl idiom, to hide the private interface.
    • Additionally you could export the string in the form of chars

    Hide your original dog:

    class Dog_Impl // your original class
    {
    
    public:
      Dog_Impl(std::string name):_name(name){}
      ~Dog_Impl(){}
    
      string::get_name();
    private:
      std::string _name;
    
    };
    

    Put this into your API:

    class Dog_Impl; // fwd declaration
    
    class PETS_EXPORT_API Dog {
      public:
        Dog(const char *name);
        ~Dog();
        const char *get_name();
    
      private:
        Dog_Impl *pImpl;
    };
    

    The implementation should simply pass all public & protected interface to the pImpl:

    Dog::Dog(const char *name) 
    {
      pImpl = new Dog_Impl(name);
    }
    
    Dog::~Dog()
    { 
      delete pImpl;
    }
    
    const char *Dog::get_name()
    {
      return pImpl->get_name().c_str(); 
    }