[Solved] In C++, why should I use “new” if I can directly assign an integer to the pointer without using “new”? [closed]


int *ptr_a = 1;doesn’t create a new int, this creates a pointer ptr_a and assigns a value of 1 to it, meaning that this pointer will point to the address 0x00000001. It’s not an integer. If you try to use the pointer later with *ptr_a = 2, you will get a segmentation fault because the pointer doesn’t point to an allocated memory space (in this precise case, it points to kernel memory, which is a no-no).

A good principle nowadays is to used std::unique_ptr<int> ptr_a = std::make_unique<int>(1)which will allocate a new int with a value of 1 and deallocate the memory once ptr_a gets out of scope.

1

solved In C++, why should I use “new” if I can directly assign an integer to the pointer without using “new”? [closed]