Reputation: 97
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.
Upvotes: 0
Views: 121
Reputation: 96810
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.
Upvotes: 3