https://www.fluentcpp.com/2019/07/23/how-to-define-a-global-constant-in-cpp/
偶然看到這篇,我其實覺得他寫錯
這部分
Each file has its own version of焏. This is a problem for three reasons:
it is undefined behaviour (objects must be defined only once in C++),
??????真的undefined嗎?有沒有什麼表格或網址整理ub...之前看到說把東西寫在
namespace std也是ub...也太多很容易就寫出來的ub了吧
it uses more memory,
if the constructor (or destructor) of曱温as side effects, they will be execute
d twice.
這句看不懂,什麼是side effect在這裡?
他的範例我唯一能看出問題的就是你沒辦法保證cout比他的x先初始化
其他他說執行兩次cstor不是很正常嗎?
我只記得const自帶static,所以預設是internal linkage
https://en.cppreference.com/w/cpp/language/cv
的Note也是這樣寫
但他說是ub 我覺得很奇怪…..
最後他提到inline,
inline跟extern效果一樣,意思是c++鼓勵使用inline而不是extern嗎
謝謝
作者:
LPH66 (-6.2598534e+18f)
2019-07-25 17:44:00執行兩次 ctor 正是他的第三點在說的你以為只有一個全域變數其實有兩個其證據即是建構子被執行了兩次那在同一支程式裡有兩個同名字的不同全域變數即是 UB 了這是明確違反 one-definition rule 的 UB後半篇文章的 inline (C++17) 和 extern (pre-C++17)它們的作用並不一樣: "It looks somewhat similar toinline, but its effect is very different."