On Wednesday, 14 November 2018 10:45:12 UTC+2, Christiano wrote:
> I tried several ways but I could not make the program access my function when I use the X[10].
> How can I do it?
That is next to never needed. What you try to actually do?
Something like that will work:
#include <iostream>
#include <vector>
struct X {};
void *operator new(size_t sz, X* p)
{
std::cout << "Placement new to X* for size " << sz << "\n";
return p;
}
void *operator new[](size_t sz, X* p)
{
std::cout << "Placement new[] to X* for size " << sz << "\n";
return p;
}
int main()
{
std::vector<X> x(7707);
new(&x.front()) char;
std::cout << "----------------------------------\n";
new(&x.front()) char[42];
std::cout << "-W-O-R-K-S------------------------" << std::endl;
}
Note that without knowing difference between new and new[]
(and delete and delete[]) there are chances that you don't
understand even most mundane points of dynamic memory
management correctly. Read up there. Tricks like placement
news and even overriding such are likely too early to study.
Better leave *all* memory management to standard library
containers and smart pointers and avoid writing any C++ code
that contains keywords "new" or "delete" whatsoever. With
such code it is easier to become employed currently than
with seriously confused code.