我才发现,原来为basic_string<char>
从在GCC 4.9实施STL(使用MinGW的-W64)的默认分配不使用全球operator new()
但也许直接malloc
,但在MSVC 11实施(VS 2012 )使用它。STL实现之间分配策略的区别?
还在CentOS下尝试了gcc 4.4.6,并且按预期调用了该运算符。
为什么会有这样的差异,而不是MSVC方法的正确方法?我希望能够通过提供我自己的operator new()
来跟踪STL完成的每个分配。
这是我的测试代码:
#include <limits>
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <memory>
#include <map>
using namespace std;
template<typename T>
struct MallocAllocator
{
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
pointer allocate(size_type n, const void* = 0) {
cout << "Custom: " << sizeof(value_type) * n << endl;
return static_cast<pointer>(malloc(sizeof(value_type) * n));
}
void deallocate(pointer ptr, size_type) {
free(ptr);
}
// boilerplate follows
MallocAllocator() {}
MallocAllocator(const MallocAllocator&) {}
size_type max_size() const throw() { return std::numeric_limits<std::size_t>::max()/sizeof(T); }
template <typename Other>
MallocAllocator(const MallocAllocator<Other>&) {}
MallocAllocator& operator=(const MallocAllocator&) { return *this; }
template <class Other>
MallocAllocator& operator=(const MallocAllocator<Other>&) { return *this; }
template <typename Other>
struct rebind { typedef MallocAllocator<Other> other; };
pointer address(reference ref) const {
return &ref;
}
const_pointer address(const_reference ref) const {
return &ref;
}
void construct(pointer ptr, const value_type& val) {
::new(ptr) value_type(val);
}
void destroy(pointer ptr) {
ptr->~value_type();
}
};
template <typename T, typename U>
inline bool operator==(const MallocAllocator<T>&, const MallocAllocator<U>&) {
return true;
}
template <typename T, typename U>
inline bool operator!=(const MallocAllocator<T>& a, const MallocAllocator<U>& b) {
return !(a == b);
}
void *operator new(size_t s) {
cout << "Global: " << s << endl;
return (void*)malloc(s);
}
void *operator new[](size_t s) {
cout << "Global: " << s << endl;
return (void*)malloc(s);
}
int main(int argc, char** argv) {
//basic_string<char, char_traits<char>, MallocAllocator<char> > s;
basic_string<char> s;
s = "dfasdf";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += ".";
s += "dfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfsdfasdfsdfasfs";
cout << s << endl;
#ifdef _MSC_VER
system("pause");
#endif
return 0;
}
与MinGW的-W64 GCC:当我使用自定义的分配器,我看到了分配。当我不使用它时,我什么都看不到。
FWIW - 它确实使用了全球新从GCC 4.8.1 - 见[ideone.com(http://ideone.com/Akj19D) - 必须是最近的变化。使我怀疑它是否试图'realloc'而不是每次新/复制/删除.... – 2014-09-05 08:41:07
我刚刚尝试** ** gcc 4.8.1 **从** MinGW-w64 **,并再次没有工作。但从Linux下的普通gcc(任何版本),它的工作原理如下。 – onqtam 2014-09-05 08:47:20
@blender。它可能是共享DLL中导致此错误的mingw-w64运行时。我会在周一再次选择它,并尝试更多静态和共享链接的组合等。我认为它们都支持在我的mingw-build中。 – Niall 2014-09-05 17:33:46