c ++ small problem (a): An interesting question and std_new_handler () to use

C ++ play today when it came to an interesting question, and later when aware of the problem and find the cause of their own has always been the habit of ignoring compiler warnings. Procedures are as follows:

#include<iostream>
#include<cstdlib>
#include<new>
void no_memory(){
    std::cout <<"Failed to allocate memory!\n";
    std::exit(1);
}

int main () {
    std::set_new_handler(no_memory);
    std::cout << "Attempting to allocate 5 TiB...";
    char * p = new char[1024*1024*1024*1024*5];
    std::cout  << "OK\n";
    delete[] p;
    return 0;
}

The above procedure, the Qt compiled to run on, the following results

 

 

 You can see, the 5T space, can be assigned successfully. According to my computer hard drive 16G memory + 1.5T, why can assign le success. Baffled.

Later use g ++ to compile, output warning information is shown:

 

 

Ah, it overflowed. C ++ accordance with all the literals whole, which types are int type, if you do the arithmetic operation result exceeds the maximum value of the int type, it is recalculated. So * 1024 1024 * 1024 * 5 = 0; this operation indeed this new allocation of space 0 can be successfully size.

As long as the type to unsigned long long type, you can get the desired results.

 

Again introduce  set_new_handler (FUNCTION_POINTER) , this function is defined in  < new > file used to set the function allocates space when the new error, to be performed. You can be specified by the function pointer. If function_pointer parameter is empty, after the new allocation fails, it will execute the default handler function that will throw bad_alloc exception.

 

Guess you like

Origin www.cnblogs.com/mindulmindul/p/12239983.html