gpt4 book ai didi

C++ 静态成员

转载 作者:太空宇宙 更新时间:2023-11-04 14:34:38 24 4
gpt4 key购买 nike

我有以下代码:

void Foo() {

static std::vector<int>(3);

// Vector object is constructed every function call

// The destructor of the static vector is invoked at
// this point (the debugger shows so)
// <-------------------

int a;
}

然后我在某处按顺序多次调用 Foo

为什么在每次调用 Foo() 时都会构造 vector 对象,为什么在 static ... 声明之后立即调用析构函数?


更新:

我试图实现函数一次调用机制,我认为写一些类似的东西

static core::CallOnce(parameters) 其中 CallOnce 是一个类名会很好。

在我看来,编写 static core::CallOnce call_once(parameters) 看起来更糟,但是好吧,在这种情况下我无法对它做任何事情。

谢谢。

最佳答案

您的变量需要一个名称:

static std::vector<int> my_static_vector(3);

关于C++ 静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com