c++ - Pointer returned by overloaded new is changed -


this question has answer here:

i have come across bizarre problem , have created simple program in order demonstrate it. know code doesn't make sense, highlight don't understand.

#include <iostream> using namespace std;  class tempclass{ public:     float n;     tempclass(){};     ~tempclass(){} //very important line     void* operator new[](size_t size); };   void* tempclass::operator new[](size_t size){     tempclass* a;     a= ::new tempclass[2];     (int = 0; < 2; i++)     {         a[i].n = i*10;     }     cout << << endl;     return a; }   int main(){     tempclass* a;     = new tempclass[2];     cout << << endl;     cout << a[0].n << endl;     return 0; } 

in code, have overloaded operator new class have created. however, behaviour of function changes, depending on whether include destructor of class or not. have noticed, if don't include destructor, works fine, whereas if did, returned value of pointer a increased 8 @ times. therefore, in example, last cout of program print 20 if include destructor , 0 if don't, @ times. why happen?

array-new-expressions pass unspecified amount of overhead allocation function (i.e. operator new overload). allow implementation record number of array elements, destructors can called on deletion.

if implementation detects class doesn't need destructors called (because trivially destructible), may choose not require same amount of overhead otherwise.

the formal wording 8.3.4[expr.new]p11:

when new-expression calls allocation function , allocation has not been extended, new- expression passes amount of space requested allocation function first argument of type std::size_t. that argument shall no less size of object being created; may greater size of object being created if object array. [...]

note overhead unspecified, in principle different @ every call! (this reason placement-array-new unusable.) however, itanium abi many implementations use specific in how "array cookie" works, , matches experience.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -