为什么构造函数只调用一次?

use*_*447 1 c++ c++14

我有一些代码。

#include <iostream>
#include <memory>
using namespace std;

class A
{
public:
    A() { cout << "called" << endl; }
};


A* foo()
{
    static A* a = new A();
    return a;
}

int main()
{
    A *p = foo();
    cout << std::addressof(*p) << endl;

    A *pp = foo();
    cout << std::addressof(*pp) << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我调用了 foo() 两次。

但是类A构造函数调用了一次。

我知道“静态”关键字只使用相同的地址空间。

有一个“静态”关键字另一个我不知道的规范?

如果删除静态,此代码正在工作(构造函数调用两次)。

Dav*_*rtz 5

函数 static 只初始化一次。这正是static它的作用。