我已經使用了boost :: variant一段時間,現在我正在試圖弄清楚它是如何在內部工作的。我寫了一個簡單的測試,我無法理解結果。這裏是(簡化)boost ::變體對象構造計數VS銷燬計數
struct my_type
{
my_type(){ cout << (size_t)this << " construction"; }
~my_type(){ cout << (size_t)this << " destruction"; }
};
int main()
{
variant<int, my_type> x;
x = my_type();
}
這樣的程序的輸出是
140736940365327 construction <-- A
140736940365236 destruction <-- ?
140736940365327 destruction <-- A
140736940365332 destruction <-- ?
憑啥析構函數不調用多次構造?由於析構函數是通過堆調用的,我知道這可能不是段錯誤,但在我看來,這種行爲是危險的。我錯過了什麼嗎?這與boost :: variant的「備份」機制有關嗎?
向您的課堂添加複製構造函數。 – Mat 2013-02-23 12:22:23