作者liu2007 (薯)
看板C_and_CPP
标题[问题] 为什麽static 的变数不会被初始化
时间Tue Mar 25 22:11:17 2025
想问个小问题
在某一个版本之後
关於singleton的写法推荐如下
QByteArray& AlbumItem::placeholderBytes(){
static QByteArray bytes;
if (bytes.isNull()){
//....................
}
}
return bytes;
}
後来我想改用指标
QByteArray* AlbumItem::placeholderBytes(){
static QByteArray *bytes = nullptr;
if (bytes == nullptr){
//........................
}
}
return bytes;
}
本来我担心已经存在记忆体里的*bytes会被初始化为nullptr
造成非singleton的情况
并且导致有记忆体泄漏
还好测试一下并没有这样的情况发生
想请问是否是因为他检查如果该static 变数已存在於记忆体
就会跳过宣告这行程式码吗?
还是说实际上有其他动作,只是刚好结果符合我想要的呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 123.194.20.237 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1742911880.A.516.html
※ 编辑: liu2007 (123.194.20.237 台湾), 03/25/2025 22:11:47
1F:→ nh60211as: static variable 只会在第一次跑到的时候执行一次 03/25 22:21
3F:→ nh60211as: _duration#Static_block_variables 03/25 22:21
4F:→ nh60211as: 楼下支援C++标准文件 03/25 22:22
6F:→ Lipraxde: n-c-8e20e6c3c96d 03/26 08:52
7F:推 Lipraxde: 发现中文的了,该讲的差不多都有讲到XD 03/26 09:03
9F:→ bbbing: function本地的static要能保留沿用,要每次初始化那static 03/26 10:07
10F:→ bbbing: 就没意义了吧,反之我以为就是用static的目的 03/26 10:07
11F:推 descent: c++ runtime 有一部份在处理 local static object 03/26 16:01
12F:→ descent: 让 static object 只初始化一次 03/26 16:01
13F:→ descent: 大概是要让 object 的行为和 c static 变数有一样的行为 03/26 16:01
14F:推 Dracarys: 会sync但可以用-fno-threadsafe-statics关掉,然後 03/26 19:00
15F:→ Dracarys: Itanium C++ ABI有规定api让compiler生code来呼叫runti 03/26 19:00
16F:→ Dracarys: me来达成这件事 03/26 19:00
17F:推 wulouise: 不能理解你的问题,初始化完他就是nullptr, 然後qt有sma 03/27 00:49
18F:→ wulouise: rt pointer所以本来就不会leak吧 03/27 00:49
19F:→ wulouise: 问题是你改成static ptr谁要负责帮你new?没有data race? 03/27 00:50
20F:→ wulouise: 你的if 里面要做什麽,这个function要做什麽描述一下 03/27 00:51