我有这门课:
#include <cstdio>
#include <cstring>
class Number
{
int data;
public:
int get()
{
return data;
}
char* to_str(int& size)
{
static char str[10];
snprintf(str, 10, "%d", data);
size = strlen(str) + 1;
return str;
}
};
我知道返回静态数组是危险的(即不是线程安全的等),并且因为我使用的是 C++,所以我应该使用 std::string
。
我感兴趣的是它是如何工作的。由于每个方法只编译一次,然后它的代码被所有对象使用(通过不可见的第一个参数,可通过 this
指针访问),这给我留下了一个难题:静态数组是否唯一对于该类的每个对象还是为所有对象共享?再说一遍,我对机制感兴趣(出于学习目的),而不是对良好的编码实践感兴趣(上面的代码绝对不是好代码)。
最佳答案
Since each method is only compiled once
它被编译了几次,因为它是一个内联定义(假设您的类位于 header 中并且它被多个翻译单元 (TU) 包含)。
如果您在 TU(.cpp
文件)中提供定义,那么您是对的。
and its code is then used by all objects (through the invisible first argument, accessible as the this pointer)
注意,this
指针与静态数据成员和静态局部变量是否共享无关,无论代码是否在程序中共享。
is that static array unique for each object of that class or is it shared for all objects?
方法(成员函数)中的静态局部变量是唯一的,即在所有实例之间共享(与任何其他函数相同)。
关于c++ - 成员函数中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57947834/