Somebody told me that I don't necessarily have to delete struct pointer manually.
From what I understand you must delete
everything that is allocated with new
, even structs, right?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- Why are memory addresses incremented by 4 in MIPS?
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Right, you must. As with everything else, if you allocated memory fore something, you are responsible for releasing it.
Of course when you
new
any type (int
,char
, ...,MyClass
,MyStruct
) you are reserving some memory, so you will need to free it later yourself.delete
for anynew
delete[]
for anynew[]
...In general, you need a
delete
for everynew
,delete []
for everynew []
,fclose
for everyfopen
and all the other varieties.Still, you need not neccessarily write it yourself, if you delegate it to a smart-pointer for example, like
unique_ptr
andshared_ptr
.You should do that on general principles anyway!
Also, there actually are a few circumstances in which never de-allocating is appropriate, like if you store some data you will have to keep until the end of the program, unless the destructor does something important.
Actually, there's no need to bother sweeping the carpets when the house gets demolished, and it would have a negative performance impact, which might easily get unacceptibly big.
Think about it "Come here (page in), so I can dismiss you (free)." seems a bit pointless or even spiteful.
You could use smart pointers as for example
std::unique_ptr
. It would call its own deleter when the object of the structure was destroyed.Otherwise you indeed have to call operator delete or delete [] provided that the structure is the owner of the pointer.