c++ - Temporary object not destroyed correctly? -



c++ - Temporary object not destroyed correctly? -

see code here:

class test { int n; int *j; public: test(int m) { n = 12; j = new int; cin >> *j; } void show() { cout << n << ' ' << *j << endl; } ~test() { delete j; } }; int main() { test var = 123; var.show(); homecoming 0; }

in programme compiler should complain double deleting of j. first delete done when temporary object temporary(123) destroyed. sec delete done when var object destroyed. working fine?

does mean temporary object not phone call destructor?

the contentious line this:

test var = 123;

the relevant standard text (that pundits in comments referencing), believe, (8.5, "declarators"):

the function selected called initializer look argument; if function constructor, phone call initializes temporary of cv-unqualified version of destination type. temporary rvalue. result of phone call (which temporary constructor case) used direct-initialize, according rules above, object destination of copy-initialization. in cases, an implementation permitted eliminate copying inherent in direct-initialization constructing intermediate result straight object beingness initialized;

indeed, in 12.6, illustration of this:

complex f = 3; // build complex(3) using // complex(double) // re-create f

thus, in utilize of =, implementation probably straight constructing object , eliminating intermediate temporary exclusively (and, comments have noted, do).

this class doesn't re-create properly, creating re-create of (and freeing re-create , original) result in double delete (and crashes, undefined behavior, etc.). because no copies created, scenario not happen above.

c++ memory-management temporary-objects

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -