メモリ割り当てを追跡するための追跡クラスを作成しようとしています。例えば、アプリケーション内で何バイトが割り当てられているかを印刷する。新しい/削除演算子を使用する変数の場合。私はoperator new/deleteを使うことができました。しかし、スマートポインタによって割り当てられるメモリはどうですか?スマートポインタを使用するときにメモリ割り当てを追跡する方法
#include <memory>
#include <iostream>
using namespace std;
template<T>
class MemoryTracking : std::enable_shared_from_this<MemoryTracking<T> >
{
public:
static size_t s_total;
void* operator new (const size_t s)
{
s_total += s;
return ::operator new[](s);
}
void* operator new[](const size_t s)
{
s_total +=s;
return ::operator new[](s);
}
void delete(void *p, size_t s) noexcept
{
s_total -= s;
::operator delete(p);
}
void delete[](void *p, size_t s) noexcept
{
s_total -= s;
::operator delete[](p);
}
// for shared_ptr
MemoryTracking() throw() {};
MemoryTracking(const MemoryTracking& other) throw() {};
MemoryTracking<T>& operator = (const MemoryTracking<T>& other) { return *this; }
MemoryTracking<T>& operator = (const MemoryTracking& other) { return *this; }
~MemoryTracking() {}
T* allocate(size_t n, const void* hint = 0)
{
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void deallocate(T* ptr, size_t n)
{
::operator delete(ptr);
}
template <typename U>
inline bool operator == (const MemoryTracking<U>&)
{
return true;
}
template <typename U>
inline bool operator != (const MemoryTracking<U>& obj)
{
return !(*shared_from_this() == obj);
}
};
class A : public MemoryTracking<A>
{
}
int main()
{
auto ptr = make_shared<A>();
cout << MemoryTracking::s_total << endl;
}
[この](http://stackoverflow.com/questions/9675225/boostmake-shared-is-not-calling-placement-operator-新しい)あなたの質問に答えているようです。 'make_shared'は(おそらく)グローバルプレースメントnewを使用しています。 – Sam
私は理想的には、allocate_traitsを使ってメモリを割り当てるallocate_sharedを使ってshared_ptrを作成する必要があることを知っています。しかし、私はそれがどれほど正確にできるのか分かりません。また、allocate_uniqueがないので、unique_ptrによって割り当てられたメモリをどのように追跡するのかよくわかりません。 – r0ng