c++ - 创建没有默认构造函数的对象数组

标签 c++ new-operator dynamic-arrays

我在很多地方读到,在 C++ 中,不能使用 new[] 运算符来创建没有默认构造函数的对象数组。我也明白我可以使用 vector 来轻松实现这一点。

但是,我尝试了以下代码,它似乎使我能够在没有默认构造函数的情况下对对象数组使用 new[] 运算符:

struct mystuff{
    int data1, data2;

    mystuff(int a){
        data1 = a;
        data2 = 10;
    }
    mystuff(int a, int g){
        data1 = a;
        data2 = g;
    }
};

int main(){
    mystuff *b = static_cast<mystuff*> (::operator new (sizeof(mystuff[5]))); //allocate memory
    for (int i = 0; i < 5; i++){
        std::cout << &b[i] << std::endl; //addresses of allocated memory
    }
    new (b + 1)mystuff(5); //initialize one of the values in the array with non default constructor
    new (b + 3)mystuff(10, 15); //initialize one of the values in the array with non default constructor
    std::cout << "\n" << std::endl;
    for (int i = 0; i < 5; i++){
        std::cout << &b[i] << std::endl; //addresses of allocated memory after constructor
    }

    std::cout << "Values of constructed objects" << std::endl;
    std::cout << b[1].data1 << "," << b[1].data2 << std::endl;
    std::cout << b[3].data1 << "," << b[3].data2 << std::endl;

    std::cin.get();

    delete[] b;
    return 0;
}

如果有人能告诉我这是否是合法的事情,或者显示的内容是否因我没有意识到的某种原因而非常错误和危险(即我以某种方式在这个特定的地方创建了内存泄漏),我将不胜感激。示例)。

非常感谢

最佳答案

您可以为动态数组提供初始值设定项,也可以填充 vector :

mystuff * b = new mystuff[3] { mystuff(1), mystuff(2, 3), mystuff(4) };
// *b is leaked

std::vector<mystuff> const c { mystuff(1), mystuff(2, 3), mystuff(4) };

关于c++ - 创建没有默认构造函数的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26497811/

相关文章:

c++ - 袖口 : How to calculate the fft when the input is a pitched array

c - 动态数组在通过引用传递时交换列和行

C++ while循环从输入文件中读取

c++ - Pancake Glutton 寻找数组中的最大值

c++ - 用 C++ 为嵌入式系统实现状态机

c++ - 新建、删除、malloc 和免费

c - 调整动态数组大小后出现段错误

c# - 信号量实现

c++ - 指针和新运算符

c++ - 为什么要替换默认的 new 和 delete 运算符?