C++:使用自定义分配器时的高效swap()

jww*_*jww 14 c++ templates swap

对我来说,它似乎是C++模板的月份......

我有一个SecureString.SecureString看起来就像一个std :: string,除了它使用一个自定义分配器,它将销毁归零:

class SecureString
{
public:
  typedef std::basic_string< char, std::char_traits<char>, zallocator<char> > SecureStringBase;
  typedef zallocator<char>::size_type size_type;
  static const size_type npos = static_cast<size_type>(-1);
  ....
private:
  SecureStringBase m_base;
};
Run Code Online (Sandbox Code Playgroud)

有关SecureString的完整代码,请访问http://code.google.com/p/owasp-esapi-cplusplus/source/browse/trunk/esapi/util/SecureString.h ; 可以在http://code.google.com/p/owasp-esapi-cplusplus/source/browse/trunk/esapi/util/zAllocator.h找到分配器的代码.

目前,我们有一个swap定义,它将std :: string作为参数:

void SecureString::swap(std::string& str)
{
  SecureStringBase temp(str.data(), str.size());
  m_base.swap(temp);
  str = std::string(temp.data(), temp.size());
}
Run Code Online (Sandbox Code Playgroud)

我觉得我错过了一个机会,swap因为底层类型只有分配器才有所不同.任何人都可以看到避免临时的方法吗?是否可以使用它来rebind加快运行速度?

编辑:SecureString::swap(std::string& str)现在不见了.对于后代,已经留下了对该主题中的功能的引用.

杰夫

Mat*_* M. 9

很不幸的是,不行.

这不是rebind为了什么.rebind因为分配器用于分配一种类型的对象,而std::allocator<T>在STL中只分配一种类型().

但是,有一个技巧.当你实例std::list<T, std::allocator<T>>,例如,则allocator没有分配TS,它有分配一些内部结构,而不是像__list_node<T>,那就是当rebind投入使用时,它会创建一个新的allocator,这个先例的兄弟(他们只能由不同模板参数,可能共享相同的内存池.

但是,在你的情况下,你的分配器和std::string分配器是不同的,因此它们不能交换内存.所以你必须做一份副本.

您可以优化void swap(SecureString&, SecureString&)操作,但不能优化此操作.

一个问题:为什么不typedef std::string<char, SecureAllocator<char>> SecureString;呢?