[
next
] [
prev
] [
prev-tail
] [
tail
] [
up
]
1.1.3.2
new basic knowledge
There are four parts of knowledge about new operator:
throw bad_alloc exception.
no throw, but return nullptr(since c++11)
placement new(not allocate, just ctor)
operator new(just allocate, no ctor)
MyClass
*
p1
=
new
MyClass
;
//
1:
if
fail
,
through
bad_alloc
MyClass
*
p2
=
new
(
std
::
nothrow
)
MyClass
;
//
2:
no
throw
new
(
p2
)
MyClass
;
//
3:
placement
new
//
4:
operator
new
MyClass
*
p3
=
(
MyClass
*
)
::
operator
new
(
sizeof
(
MyClass
));
//
allocates
memory
by
calling
:
operator
new
//
but
does
not
call
MyClass
’
s
ctor
new will call constructor function of a class, but malloc will not call constructor function.
So in C++, you should use new instead of
malloc.
If you use new int[100], use delete [];
Any time you want to use new to
allocate an array, ask yourself if you can replace it with vector or
string.
[
next
] [
prev
] [
prev-tail
] [
front
] [
up
]