#include "boost/shared_ptr.hpp"
#include "iostream"
#include "boost/thread.hpp"

class Test {

private:
    Test(int n) {
        std::cout << "build Test " << n << "begin"<<std::endl;
        sleep(n);
        std::cout << "build Test " << n << "end"<<std::endl;
    }
public:


    static boost::shared_ptr<Test> getTest(int n) {
        static boost::shared_ptr<Test> instance = boost::shared_ptr<Test>(new Test(n));
        std::cout << static_cast<const void *>(instance.get()) << "end"<<std::endl;
        return instance;
    }
};

int main() {

    boost::thread th1([]() {
        auto t1 = Test::getTest(3);
    });
    th1.join();
    boost::thread th2([]() {
        auto t2 = Test::getTest(2);
    });
    th2.join();
    boost::thread th3([]() {
        auto t3 = Test::getTest(1);
    });
    th3.join();
    return 1;
}

输出结果

build Test 3begin
build Test 3end
0x7fe1480008c0end
0x7fe1480008c0end
0x7fe1480008c0end

构造函数只被调用了一次,静态代码快构造函数只能有一个线程访问。

03-30 10:35