Created
November 5, 2016 07:44
-
-
Save itczl22/e3ba34614be903565fde4eafe6e65da1 to your computer and use it in GitHub Desktop.
定位new
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 定位new | |
*/ | |
#include <iostream> | |
using namespace std; | |
char g_addr[100]; | |
int main() { | |
// 把内存分配到全局区 | |
//int* p = new(g_addr)int; | |
int* p = new(g_addr)int(3); //赋初值 | |
*p = 2; | |
cout << static_cast<void*>(g_addr) << " " << static_cast<void*>(p) << " " << *p << endl; | |
// 把内存分配到栈区 | |
char l_addr[100]; | |
p = new(l_addr)int[2]; | |
p[0] = 1; | |
p[1] = 2; | |
cout << static_cast<void*>(l_addr) << " " << static_cast<void*>(p) << " " << p[0] << " " << p[1] << endl; | |
// 把内存分配到堆区 | |
char *h_addr = new char[100]; | |
p = new(h_addr)int[2]{4, 5}; | |
cout << static_cast<void*>(h_addr) << " " << static_cast<void*>(p) << " " << p[0] << " " << p[1] << endl; | |
delete[] h_addr; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment