IT박스

기본 생성자가 내장 유형을 초기화합니까?

itboxs 2020. 6. 1. 19:23
반응형

기본 생성자가 내장 유형을 초기화합니까?


컴파일러에서 만든 기본 생성자가 내장 형식을 초기화합니까?


클래스의 암시 적으로 정의 된 클래스의 기본 생성자는 내장 유형의 멤버를 초기화하지 않습니다.

그러나 경우에 따라 클래스 인스턴스의 초기화는 다른 방법으로 수행 될 수 있음을 명심해야합니다. 기본적으로 생성 자나 생성자가 아닙니다.

예를 들어 클래스의 C경우 구문이 C()항상 기본 생성자를 호출 한다는 잘못된 믿음이 널리 퍼져 있습니다. 그러나 실제로 구문 C()클래스 인스턴스의 소위 값 초기화수행 합니다. 사용자가 선언 한 경우에만 기본 생성자를 호출합니다 . (C ++ 03에 있습니다. C ++ 98에서는-클래스가 비 POD 인 경우에만). 클래스에 사용자가 선언 한 생성자 C()가없는 경우 컴파일러에서 제공 한 기본 생성자를 호출하지 않고 생성자가 전혀 포함되지 않은 특수한 종류의 초기화를 수행 C합니다. 대신 클래스의 모든 멤버를 직접 값으로 초기화합니다. 내장 유형의 경우 초기화가 0이됩니다.

예를 들어, 클래스에 사용자 선언 생성자가없는 경우

class C { 
  int x;
};

컴파일러는 암시 적으로 하나를 제공합니다. 컴파일러 제공 생성자는 아무 것도 수행하지 않으므로 초기화되지 않습니다.C::x

C c; // Compiler-provided default constructor is used
// Here `c.x` contains garbage

그럼에도 불구하고 다음 초기화 x 명시 적 ()이니셜 라이저 를 사용하기 때문에 0 으로 초기화됩니다.

C c = C(); // Does not use default constructor for `C()` part
           // Uses value-initialization feature instead
assert(c.x == 0);

C *pc = new C(); // Does not use default constructor for `C()` part
                 // Uses value-initialization feature instead
assert(pc->x == 0);

()이니셜 라이저 의 동작은 C ++ 98과 C ++ 03 사이에서 일부 다르지만이 경우에는 다릅니다. 위의 클래스의 C경우 동일합니다. ()initializer는 0의 초기화를 수행하지 않습니다 C::x.

생성자를 포함하지 않고 수행되는 초기화의 다른 예는 물론 집계 초기화입니다.

C c = {}; // Does not use any `C` constructors at all. Same as C c{}; in C++11.
assert(c.x == 0);

C d{}; // C++11 style aggregate initialization.
assert(d.x == 0);

모든 실제적인 목적을 위해-아닙니다.


그러나 기술적으로 C ++ 표준을 준수하는 구현의 경우, 개체가 POD인지 여부와 초기화 방법에 따라 달라집니다. C ++ 표준에 따르면 :

MyNonPodClass instance1;//built in members will not be initialized
MyPodClass instance2;//built in members will be not be initialized
MyPodClass* instance3 = new MyPodClass;//built in members will not be initialized
MyPodClass* instance3 = new MyPodClass() ;//built in members will be zero initialized

그러나 실제 환경에서는이 기능이 제대로 지원되지 않으므로 사용하지 마십시오.


표준의 관련 부분은 섹션 8.5.5 및 8.5.7입니다.


나는 당신이 무엇을 의미하는지 잘 모르겠지만,

struct A { int x; };

int a; // a is initialized to 0
A b;   // b.x is initialized to 0

int main() {
    int c;         // c is not initialized
    int d = int(); // d is initialized to 0

    A e;           // e.x is not initialized
    A f = A();     // f.x is initialized to 0
}

내가 "초기화되지 않았다"고 말할 때마다 컴파일러는 일관된 값을 제공하지만 표준에는 필요하지 않습니다.

A lot of hand-waving gets thrown around, including by me, about how built-in types "in effect" have a default constructor. Actually default initialization and value initialization are defined terms in the standard, which personally I have to look up every time. Only classes are defined in the standard to have an implicit default constructor.


As per the standard, it doesn't unless you explicitly initialize in initializer list


As previous speakers have stated - no, they are not initialized.

This is actually a source for really strange errors as modern OSs tend to fill newly allocated memory regions with zeroes. If you expect that, it might work the first time. However, as your application keeps running, delete-ing and new-ing objects, you will sooner or later end up in a situation where you expect zeroes but a non-zero leftover from an earlier object sits.

So, why is this then, isn't all new-ed data newly allocated? Yes, but not always from the OS. The OS tends to work with larger chunks of memory (e.g. 4MB at a time) so all the tiny one-word-here-three-bytes-there-allocations and deallocations are handled in uyserspace, and thus not zeroed out.

PS. I wrote "tend to", i.e. you can't even rely on success the first time...


Technically it does initialize them -- by using their default constructor, which incidentally does nothing but allocate the memory for them.

If what you wanted to know is whether or not they are set to something sane like 0 for ints, then the answer is "no".


No. The default constructor allocates memory and calls the no-argument constructor of any parents.

참고URL : https://stackoverflow.com/questions/2417065/does-the-default-constructor-initialize-built-in-types

반응형