gpt4 book ai didi

c++ - 编译时判断对象是否有自动存储时长的方法

转载 作者:太空狗 更新时间:2023-10-29 21:44:48 24 4
gpt4 key购买 nike

我希望能够在编译时强制执行特定类型只能用于创建具有自动存储持续时间的对象。

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++ 中实现此目的?

编辑:次要目标是允许 Array 的分配策略通过放入 AutoAllocator 中的任一个进行透明切换或默认 std::allocator .

typedef Array<int, std::allocator<int>> DynamicArray;

假设有大量代码已经使用了 DynamicArray .

最佳答案

这是不可能的。假设您创建了一个将 this 作为成员的类型。当编译器为该类型的构造函数生成代码时,它不知道对象在哪里被创建,完整的对象是在栈中,还是在堆中?

你需要以不同的思维方式解决你的问题,例如,你可以将分配器传递给对象的构造函数(BSL 的方式)并且可能默认为安全分配器(基于 new-delete ),然后对于那些后进先出分配器是更好选择的用例,用户可以明确请求它。

这与编译器错误不同,但它足够明显,可以在代码审查时检测到。

如果您真的对分配器的有趣用途感兴趣,您可能想看看标准库的 BSL 替代品,因为它允许传播到容器成员的多态分配器。在 BSL 世界中,您的示例将变为:

// Assume a blsma::Allocator implementing LIFO, Type uses that protocol
LifoAllocator alloc; // implements the bslma::Allocator protocol
Type l(&alloc); // by convention bslma::Allocator by pointer
static Type s; // defaults to new-delete if not passed
new (&alloc) Type(&alloc); // both 'Type' and it's contents share the allocator
// if the lifetime makes sense, if not:
new Type; // not all objects need to use the same allocator
bsl::vector<Type> v(&alloc);
v.resize(1); // nested object uses the allocator in the container

一般来说,使用分配器并不简单,您必须注意对象之间以及分配器之间的相对生命周期。

关于c++ - 编译时判断对象是否有自动存储时长的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19247063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com