【问题标题】:C++: Simple construct-on-first-use not workingC++:简单的首次使用构造不起作用
【发布时间】:2013-07-27 00:20:13
【问题描述】:

根据我的阅读,“首次使用时构造”使用方法在第一次调用该方法时创建一个静态变量,然后在后续方法调用中返回相同的变量。我在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 次。这应该发生吗?我认为析构函数应该只在程序结束时调用。 我怀疑我可能以某种方式弄乱了我的计算机,但我可能只是在我的代码中犯了一个简单的错误......有什么想法吗?

【问题讨论】:

    标签: static constructor destructor


    【解决方案1】:
    1. 请说明您对代码的期望。

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

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

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

    通常,如果您没有实现一个复制构造函数,编译器应该生成一个,尽管它不会打印自定义消息,这不足为奇。

    【讨论】:

    • 我想知道为什么析构函数被多次调用,即使 testClass t 是静态的。抱歉,我会将其添加到我的问题中
    • 好吧,无论如何,我的回答应该已经向您解释了;)(对象是通过复制构造函数创建的)
    • 啊,应该是testClass & test() {。抱歉,我习惯用 Java 编码 :P 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2011-04-14
    相关资源
    最近更新 更多