c++ - SomeClass* initialEl = new SomeClass[5];

标签 c++ class memory-management dynamic-memory-allocation dynamic-arrays

应该 SomeClass* initialEl = new SomeClass[5];必须编译,假设 SomeClass 没有非公开声明的默认构造函数?考虑:

/*
 * SomeClass.h
 *
 */

#ifndef SOMECLASS_H_
#define SOMECLASS_H_

class SomeClass
{

public:
    SomeClass(int){}
    ~SomeClass(){}
};

#endif /* SOMECLASS_H_ */


/*
 * main.cpp
 *
 */

#include "SomeClass.h"

int main()
{
    SomeClass* initialEl = new SomeClass[5];

    delete[] initialEl;

    return 0;
}

最佳答案

假设 SomeClass 有一个可公开访问的默认构造函数,是的。

注意有区别

  1. 有一个可公开访问的默认构造函数(我说的)和
  2. 没有非公开声明的默认构造函数(如您所说)

对于下面的类 2. 是真的但是 1. 不是:

class A {
    SomeClass(const SomeClass&) {}
};

这是由于 §12.1/5 (C++03):

If there is no user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared default constructor is an inline public member of its class.


随着您的更新,SomeClass 没有默认构造函数。您没有声明一个构造函数,因为您声明了另一个构造函数,编译器也不会隐式声明它。

如果你需要一个,你必须自己实现它:

class A {
public:
    SomeClass(int) {}
    SomeClass() {}
};

或者让另一个构造函数符合默认构造函数的条件:

class A {
public:
    SomeClass(int=0) {}
};

关于c++ - SomeClass* initialEl = new SomeClass[5];,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3258269/

相关文章:

c++ - 如何在返回类型函数模板的特化中使用派生类型? ("couldn' t 推断模板参数")

c++ - 指针的常见用途?

java - Reflection API 中 new Class[0] 的含义

class - GO接口(interface)中的多态性

ios - AlamofireImage 没有释放内存

c++ - 我可以像使用父类指针一样使用继承的类指针吗?

c++ - 添加 Sprite 时窗口关闭

以泛型类作为参数的 Java 方法

java - 垃圾收集和线程

iphone - 在模态视图中收到内存警告 - 父 View Controller 的对象被释放。如何预防?