c++:使用自定义分配器时高效的swap()
C++: efficient swap() when using a custom allocator
这似乎是我的c++模板之月…
我有一个安全字符串。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;
};
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());
}
我觉得我在swap
中错过了一个机会,因为底层类型只因分配器而不同。有人能想到避免临时的方法吗?是否有可能使用rebind
使此运行更快?
编辑:SecureString::swap(std::string& str)
现在不见了。本文中对函数的引用已保留,以供后人参考。
不幸的是…没有。
这不是rebind
的作用。之所以使用rebind
,是因为分配器在STL中只分配一种类型的对象(std::allocator<T>
)。
然而,有一个技巧。例如,当您实例化std::list<T, std::allocator<T>>
时,allocator
不必分配T
s,它必须分配一些内部结构,而不是像__list_node<T>
一样,这就是当rebind
被使用时,它创建了一个新的分配器,先例的兄弟(它们只是模板参数不同,并且可能共享相同的内存池)。
std::string
分配器是不同的,因此它们不能交换内存。所以你要做一个拷贝。
您可以优化void swap(SecureString&, SecureString&)
操作,但不能优化这个操作。
一个问题:为什么不是typedef std::string<char, SecureAllocator<char>> SecureString;
?
- C++中高效的大型稀疏块压缩线性方程
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 如何在C++中高效地构造随机骰子
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- 如何实现高效的算法来计算大型数据集的多个不同值?
- 更高效地在微控制器上对C++进行基准测试
- 从C++无序集合中高效提取元素
- 我可以使用 std::vector::swap 来修改共享向量吗?
- Valgrind 在 std::string::swap 中报告 SIGILL
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- C++中特征对角矩阵类型的高效存储
- 对函数的 out 字符串参数使用 swap 与赋值
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 高效简单的结构比较运算符
- 使用 Rcpp 的高效矩阵子集
- C++ 包含特征矩阵的类的高效算术运算符重载
- CUDA 高效的 nd-array(张量)切片
- a,b = b,a in python vs std::swap() in C++
- c++:使用自定义分配器时高效的swap()