[問題] const 變數在.h, undefined behavior?

作者: lovejomi (JOMI)   2019-07-24 22:19:42
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嗎
謝謝
作者: lovejomi (JOMI)   2019-07-24 23:10:00
手機複製貼上@@ 等等修改 抱歉
作者: james732 (好人超)   2019-07-24 22:38:00
你的亂碼好多 XD
作者: 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."
作者: lovejomi (JOMI)   2019-07-27 09:56:00
請問 static變數internal linkage的話 他會被mangling成 不同名字的symbol, 這樣還是違反odr嗎?

Links booklink

Contact Us: admin [ a t ] ucptt.com