Static C++;:首次使用时的简单构造不起作用

Static C++;:首次使用时的简单构造不起作用,static,constructor,destructor,Static,Constructor,Destructor,根据我所读的,“第一次使用时构造”在第一次调用该方法时使用一个方法来创建一个静态变量,然后在随后的方法调用中返回相同的变量。我在Eclipse中编写了这个简单的C++程序: #include "stdio.h"; class testClass { public: testClass() { printf("constructed\n"); } ~testClass() { printf("destructed\n"); } }

根据我所读的,“第一次使用时构造”在第一次调用该方法时使用一个方法来创建一个静态变量,然后在随后的方法调用中返回相同的变量。我在Eclipse中编写了这个简单的C++程序:

#include "stdio.h";

class testClass {
public:
    testClass() {
        printf("constructed\n");
    }

    ~testClass() {
        printf("destructed\n");
    }
};

testClass test() {
    static testClass t;
    return t;
}

int main() {
    test();
    test();
    test();
    printf("tests done!\n");
}
下面是我的结果:

constructed
destructed
destructed
destructed
tests done!
destructed
看起来main创建了一个实例,然后销毁了4次。这应该发生吗?我认为析构函数应该只在程序结束时调用。 我怀疑我可能把电脑搞砸了,但我可能只是在代码中犯了一个简单的错误……有什么想法吗

  • 请指定您对代码的期望

  • 由于它是一个静态变量,它将在函数调用之间共享,这就是为什么只调用一次它的构造函数。但是,您正在返回它的副本,这就是为什么您只能在构造函数之后看到析构函数

  • 添加一个复制构造函数,您会注意到:

    testClass(const testClass& in) { *this = in; printf("copy constructor\n");
    

    通常情况下,如果您没有实现复制构造函数,编译器应该生成复制构造函数。尽管它不会打印自定义消息,但这并不奇怪。

    我想知道为什么即使testClass t是静态的,也会多次调用析构函数。对不起,我会在我的问题中加上这一点好吧,我的回答应该已经向你解释了;)(对象是通过复制构造函数创建的)啊,它应该是
    testClass&test(){
    。对不起,我习惯了用Java编码:P谢谢!