【发布时间】:2013-10-15 08:07:09
【问题描述】:
我希望能够在编译时强制特定类型只能用于创建具有自动存储持续时间的对象。
template<typename T, typename Alloc>
struct Array
{
T* data; // owned resource
Array(std::size_t size); // allocates via Alloc
~Array(); // deallocates via Alloc
};
typedef Array<int, AutoAllocator<int>> AutoArray;
void foo(AutoArray a) // ok
{
AutoArray l = AutoArray(); // ok
static AutoArray s; // error
new AutoArray(); // error
std::vector<AutoArray> v(1); // error
}
此应用程序可以为AutoArray 实例所拥有的资源选择最佳分配策略。这个想法是具有自动存储持续时间的对象所需的资源分配模式与 LIFO 资源分配器兼容。
在 C++ 中我可以使用什么方法来实现这一点?
编辑:次要目标是通过放入AutoAllocator 或默认std::allocator 来透明地切换Array 的分配策略。
typedef Array<int, std::allocator<int>> DynamicArray;
假设有大量代码已经使用DynamicArray。
【问题讨论】:
-
您可以将
operator new声明为私有,但不确定是否可以阻止静态对象。 -
+1,好问题,但我认为没有办法做到这一点。
-
@LuchianGrigore 我正在使用对象的构造函数/析构函数来分配其拥有的资源。具有静态存储持续时间的局部变量会预先分配空间,但问题是它们不是按照与 LIFO 兼容的顺序构造的。
-
@LuchianGrigore 将
operator new声明为private并不会停止堆分配,因为您可以改写::new EnforceAuto。 -
@willj 你可能想多了。您可以简单地添加评论。 :)
标签: c++ memory-management stack metaprogramming