i have a c++ code:
// includes, variables etc...
GraphStructure graphStructure;
void getInput() {
graphStructure = GraphStructure(nodesCount, edgesCount);
// HERE, the destructor is called!
graphStructure.init(nodesCount, edgesCount);
// Same code as constructor, but now its okay.
}
int main(int argc, char* argv[]) {
getInput();
}
I would like to know, why the destructor of the object is called directly after its construction. Destructors are called after end of scope of a variable, which should be after the main function end.
GraphStructure(nodesCount, edgesCount)
is a temporary instance of GraphStructure
. As such, its destructor is called when the full expression in which it is contained is evaluated (the end being at the semicolon ;
).
If it were a local instance it would be bound by the scope of getInput()
, not main()
. Its destructor would get called when the compiler has reached the end of getInput()
(just before the ending brace }
). And the destructors of any local variables in main would get called when main finishes execution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.