0
我有一个C++代码:C++构建全局变量
// 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();
}
我想知道,为什么对象的析构函数其施工后直接调用。析构函数在变量作用域的末尾被调用,它应该在主函数结束之后。
你知道...... C++没有GC,所以它不会调用析构函数,除非你告诉它 – Steve 2014-10-06 19:13:54
@Steve:不一定是真的。如果你在栈上创建一个类类型的对象,析构函数在超出作用域时或者编译器认为没有副作用时会被调用,并且在超出作用域之前可以处理它。后者是我认为在这里发生的事情。 – 2014-10-06 19:17:32
你必须遵守三个(或五个)的规则 - 写一个适当的赋值操作符 – 2014-10-06 19:30:42