是否有可能阻止对象的堆栈分配,并且只允许在堆上使用"new"进行隔离?
一种方法是将构造函数设置为私有,并且只允许通过返回指针的静态方法进行构造.例如:
class Foo { public: ~Foo(); static Foo* createFoo() { return new Foo(); } private: Foo(); Foo(const Foo&); Foo& operator=(const Foo&); };
在C++ 11的情况下
class Foo { public: ~Foo(); static Foo* createFoo() { return new Foo(); } Foo(const Foo &) = delete; // if needed, put as private Foo & operator=(const Foo &) = delete; // if needed, put as private Foo(Foo &&) = delete; // if needed, put as private Foo & operator=(Foo &&) = delete; // if needed, put as private private: Foo(); };
您可以创建构造函数private
,然后提供public
静态工厂方法来创建对象.
以下允许公共构造函数,并通过在运行时抛出来停止堆栈分配.注意thread_local
是C++ 11关键字.
class NoStackBase { static thread_local bool _heap; protected: NoStackBase() { bool _stack = _heap; _heap = false; if (_stack) throw std::logic_error("heap allocations only"); } public: void* operator new(size_t size) throw (std::bad_alloc) { _heap = true; return ::operator new(size); } void* operator new(size_t size, const std::nothrow_t& nothrow_value) throw () { _heap = true; return ::operator new(size, nothrow_value); } void* operator new(size_t size, void* ptr) throw () { _heap = true; return ::operator new(size, ptr); } void* operator new[](size_t size) throw (std::bad_alloc) { _heap = true; return ::operator new[](size); } void* operator new[](size_t size, const std::nothrow_t& nothrow_value) throw () { _heap = true; return ::operator new[](size, nothrow_value); } void* operator new[](size_t size, void* ptr) throw () { _heap = true; return ::operator new[](size, ptr); } }; bool thread_local NoStackBase::_heap = false;