Talk:cpp/memory/c/malloc
The example code is UB because it accesses int objects that were never created. See [1] for a discussion of the current state of object creation with references to the standard.
To fix the issue one would need to use placement new to create objects:
for(int n=0; n<4; ++n) // populate the array new(p1+n) int(n*n); // placement new to create objects
— Preceding unsigned comment added by 93.220.18.148 (talk • contribs)
- p0593r2 does not just point out that virtually all code that uses malloc is undefined in C++17, it's also a proposed fix. I'd say it's unclear if changing the malloc examples would be helpful given that the fix is inevitable one way or another. Maybe a note for passing language-lawyers would help? --Cubbi (talk) 14:16, 23 May 2018 (PDT)
[edit] calling the destructor of std::string
Wouldn't it be better to call the destructor of std::string as:
p[i - 1].std::string::~string();
instead of:
p[i - 1].~basic_string();
The former is keeping the use of std::string typedef as is without the need to introduce basic_string into this example.
Amirk (talk) 15:07, 12 January 2020 (PST)
- p[i - 1].std::string::~string() (without using-declaration) fails to compile in all versions of clang. I have added a using-declaration and used p[i - 1].~string(). --Fruderica (talk) 20:36, 12 January 2020 (PST)
Better yet use std::destroy_at to call the destructor on the static type of p[i-1]. IMHO explicit calls to destructor should be discouraged even more than explicit calls to new. NickH (talk) 23:25, 12 January 2020 (PST)