在构造函数初始化列表中分配内存是否有任何问题? [英] Are there any issues with allocating memory within constructor initialization lists?

查看:82
本文介绍了在构造函数初始化列表中分配内存是否有任何问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经在我的C ++程序中使用了初始化列表,但并不知道你可以分配内存。一个假设的例子)如下:

  class Test 
{
private:
int *一世;
int * j;
int count;
int * k;

public:
Test(void):i(new int),j(new int [10]),count(10),k(new int [count])
{
}

〜Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};

这样做内存分配有什么问题吗?关于初始化的顺序这里是安全的有一个参数初始化一个在同一个列表中初始化?即在我使用它之前分配 count 是安全使用,还是有一些特殊的初始化顺序,我可以堕落?

解决方案

这不是异常安全。如果 new j 抛出异常,则 Test 不被调用,因此 i 的内存不会被释放。



如果 j 的初始化程序抛出,则调用$ c> i ,这只是一个原始指针没有析构函数。所以你可以通过用一个合适的智能指针替换 i 来使它异常安全。在这种情况下, unique_ptr< int> 用于 i unique_ptr< int []& $



可以依赖初始化器它们的正确顺序(成员定义的顺序,不一定是列表中的顺序)。他们可以安全地使用已经初始化的数据成员,因此在 k 的初始化器中使用 count


I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.

So you can do something (as a contrived example) like this:

class Test
{
private:
    int* i;
    int* j;
    int count;
    int* k;

public:
    Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
    {
    }

    ~Test(void)
    {
        delete i;
        delete [] j;
        delete [] k;
    }
};

Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate count before I use it is it safe to use or is there some special initialization order I could fall foul of?

解决方案

It's not exception-safe. If the new for j throws an exception then the destructor for Test is not called, and so the memory for i is not freed.

The destructor of i is called if the initializer for j throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing i with a suitable smart pointer. In this case, unique_ptr<int> for i and unique_ptr<int[]> for j would do.

You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using count in the initializer for k.

这篇关于在构造函数初始化列表中分配内存是否有任何问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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