Programing

연산자 new는 메모리를 0으로 초기화합니다.

lottogame 2020. 11. 13. 07:44
반응형

연산자 new는 메모리를 0으로 초기화합니다.


다음과 같은 코드가 있습니다.

#include <iostream>

int main(){
  unsigned int* wsk2 = new unsigned int(5);
  std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
  delete wsk2;
  wsk2 = new unsigned int;
  std::cout << "wsk2: " << wsk2 << " " << *wsk2 << std::endl;
  return 0;
}

결과:

wsk2: 0x928e008 5
wsk2: 0x928e008 0

new0으로 메모리를 초기화하지 않는 것을 읽었습니다 . 그러나 여기에있는 것 같습니다. 어떻게 작동합니까?


두 가지 버전이 있습니다.

wsk = new unsigned int;      // default initialized (ie nothing happens)
wsk = new unsigned int();    // zero    initialized (ie set to 0)

배열에서도 작동합니다.

wsa = new unsigned int[5];   // default initialized (ie nothing happens)
wsa = new unsigned int[5](); // zero    initialized (ie all elements set to 0)

아래 의견에 대한 답변.

음 ... new unsigned int[5]()정수 0으로 만드는 것이 확실 합니까?

분명히 그렇습니다 :

[C ++ 11 : 5.3.4 / 15] : T 유형의 개체를 생성하는 new-expression은 다음과 같이 해당 개체를 초기화합니다. new-initializer가 생략되면 개체는 default-initialized (8.5)입니다. 초기화가 수행되지 않으면 개체의 값이 결정되지 않습니다. 그렇지 않으면 새로운 초기화 프로그램은 직접 초기화를위한 8.5의 초기화 규칙에 따라 해석됩니다.

#include <new>
#include <iostream>


int main()
{
    unsigned int   wsa[5] = {1,2,3,4,5};

    // Use placement new (to use a know piece of memory).
    // In the way described above.
    // 
    unsigned int*    wsp = new (wsa) unsigned int[5]();

    std::cout << wsa[0] << "\n";   // If these are zero then it worked as described.
    std::cout << wsa[1] << "\n";   // If they contain the numbers 1 - 5 then it failed.
    std::cout << wsa[2] << "\n";
    std::cout << wsa[3] << "\n";
    std::cout << wsa[4] << "\n";
}

결과 :

> g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
> g++ t.cpp
> ./a.out
0
0
0
0
0
>

operator new is not guaranteed to initialize memory to anything, and the new-expression that allocates an unsigned int without a new-initializer leaves the object with an indeterminate value.

Reading the value of an uninitialized object results in undefined behavior. Undefined behavior includes evaluating to the value zero with no ill effects but could result in anything happening so you should avoid causing it.

In C++11, the language used is that the allocated objects are default-initialized which for non-class types means that no initialization is performed. This is different from the meaning of default-initialized in C++03.


With some compilers, the debug version of new will initialise the data, but there is certainly nothing that you can rely on.

It is also possible that the memory just had 0 from a previous use. Don't assume that nothing happened to the memory between delete and new. There could be something done in the background that you never noticed. Also, the same pointer value might not be the same physical memory. Memory pages get moved and paged out and in. A pointer might be mapped to an entirely different location than earlier.

Bottom line: if you didn't specifically initialise a memory location then you can assume nothing about its contents. The memory manager might not even allocate a specific physical memory location until you use the memory.

Modern memory management is amazingly complex, but as a C++ programmer you don't really care (mostly‡). Play by the rules and you won't get into trouble.

‡ You might care if you are optimising to reduce page faults.


That's not operator new, that's the new operator. There's actually a big difference! The difference is that operator new is a function that returns raw memory; when you use the new operator, it invokes a constructor for you. It's the constructor that's setting the value of that int, not operator new.

참고URL : https://stackoverflow.com/questions/7546620/operator-new-initializes-memory-to-zero

반응형