prevent调用默认构造内部类的数组 [英] Prevent calls to default constructor for an array inside class

查看:139
本文介绍了prevent调用默认构造内部类的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在写一个偏移数组类(您idxs从去让说,100至1000,所以您创建类,考虑到这一点不浪费阵列中的第100个插槽),我遇到了一个问题。结果
如何初始化具有元素的数组c(问题是那件T可是没有高清构造函数)的类。基本上我想要的数组是完全外行。例如:

while writing a offset array class(your idxs go from lets say 100 to 1000, so you create class that takes that into account without wasting first 100 slots in the array) I ran into a problem.
How to initialize a class that has an C array of elements(problem is that T doesnt have def constructor). Basically I want the array to be totally uninitiated. Example:

class MyClass
{
    MyClass(int i)
    {

    }
};
template <typename T, size_t n, size_t offset>
struct offsetedIdxArray
{
    T data[n];// error line : error C2512: 'MyClass' : no appropriate default constructor available
    offsetedIdxArray()
    {

    }
    T& operator [](size_t pos)
    {
        return data[(pos-offset)];
    }

};

用法:

offsetedIdxArray<MyClass, 1024,offset> oia;

制作高清构造是不是选项,因为类我用的是其实库班。

Making def constructor is not the option because class I use is in fact library class.

*的编辑:* 的没有涉及到这里所描述的问题,但事实证明,我的precious库班可是没有拷贝构造函数,只需将构造函数,所以我不得不使用的unique_ptr的矢量。

* * not related to problem described here, but it turned out that my precious library class doesnt have copy ctor, just move ctor, so I had to use vector of unique_ptr.

推荐答案

要获得存储的静态大小未初始化的部分,可以使用对齐存储的​​类型化缓冲区,如的std :: aligned_storage&LT;的sizeof(T [N]),alignof(T)&GT; ::类型在C ++ 11(在C ++ 03,你需要使用的char [的sizeof(T [N])+东西] 并做比对手动更正,或使用的char [sizeof的(T [N])] 和编译器扩展指定对齐)。

To get a statically-sized uninitialized portion of storage, you can use an "untyped" buffer of aligned storage, like std::aligned_storage<sizeof(T[n]), alignof(T)>::type in C++11 (in C++03 you need to use a char[sizeof(T[n])+something] and do manual corrections for alignment, or use a char[sizeof(T[n])] and compiler extensions to specify alignment).

这意味着使用新安置的构造,并销毁明确的析构函数调用。它是由您来跟踪什么存储部分有对象(因此需要破坏),什么地方没有对象(已经不能叫上析构函数)。这也是你来照顾,当客户端请求是不是在所有初始化的元素(有一个在它应该待的地方没有对象)。

That means using placement new for constructors, and explicit destructor calls for destruction. It is up to you to track what parts of that storage have objects (and thus needs destruction) and what parts don't have objects (and can't have destructors called on). It is also up to you to cater for when the client requests an element that isn't initialized at all (there's no object at the place it's supposed to be).

另一种方法是使用的boost ::可选的组成的数组,然后你不必在意破坏,可以简单地分配新的元素,它们各自的指数。

An alternative is to use an array of boost::optionals, and then you don't have to care about destruction and can simply assign new elements to their respective index.

这篇关于prevent调用默认构造内部类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆