为了部分回答我自己的问题,以下代码
// file myvec.cc#include <gc/gc.h>#include <gc/gc_cpp.h>#include <gc/gc_allocator.h>#include <vector>class Myvec { std::vector<int,gc_allocator<int> > _vec;public: Myvec(size_t sz=0) : _vec(sz) {}; Myvec(const Myvec& v) : _vec(v._vec) {}; const Myvec& operator=(const Myvec &rhs) { if (this != &rhs) _vec = rhs._vec; return *this; }; void resize (size_t sz=0) { _vec.resize(sz); }; int& operator [] (size_t ix) { return _vec[ix];}; const int& operator [] (size_t ix) const { return _vec[ix]; }; ~Myvec () {};};extern "C" Myvec* myvec_make(size_t sz=0) { return new(GC) Myvec(sz); }extern "C" void myvec_resize(Myvec*vec, size_t sz) { vec->resize(sz); }extern "C" int myvec_get(Myvec*vec, size_t ix) { return (*vec)[ix]; }extern "C" void myvec_put(Myvec*vec, size_t ix, int v) { (*vec)[ix] = v; }使用编译时,
g++ -O3 -Wall -c myvec.cc生成带有
% nm -C myvec.o U GC_free U GC_malloc U GC_malloc_atomic U _Unwind_Resume0000000000000000 W std::vector<int, gc_allocator<int> >::_M_fill_insert(__gnu_cxx::__normal_iterator<int*, std::vector<int, gc_allocator<int> > >, unsigned long, int const&) U std::__throw_length_error(char const*) U __gxx_personality_v0 U memmove00000000000000b0 T myvec_get0000000000000000 T myvec_make00000000000000c0 T myvec_put00000000000000d0 T myvec_resize
因此,没有普通的malloc或
::operator new生成的代码中。
因此,通过使用
gc_allocator和,
new(GC)我显然可以确保在我不知情的情况下使用普通
::opertornew或
malloc不使用,并且不需要重新定义
::operator new
附录(2017年1月)
对于未来的参考(感谢谢尔盖·祖布科夫为提它的Quora在评论),也见n2670和
<memory>和垃圾收集的支持(如性病::
declare_reachable,性病::
declare_no_pointers,标准::
pointer_safety等)。但是,至少在当前的GCC或Clang中,尚未实现该功能(以琐碎但可接受的方式使其成为空操作)。



