scrap book

( ..)φメモメモ

std::queue::pop()はデストラクタがあれば呼び出す

std::queue::pop()はデストラクタを呼び出す。しかしポインタ型を格納した場合は例外。
ポインタ型そのものがデストラクタを持っていないため、らしい。
逆に実体をpop()するとスコープ抜けたときとあわせて2回呼ばれることになる。

code.cpp

#include <queue>
#include <iostream>

using namespace std;

class animal {
    string kind;
public:
    animal(string kind) {
        this->kind = kind;
        cout << "animal ctor : " << kind << endl;
    }
    ~animal() {
        cout << "animal dtor : " << kind << endl;
    }
};

int main(void)
{
    queue<animal*> q;
    q.push( new animal("dog") );
    auto dog = q.front();
    q.pop();
    delete dog;


    queue<animal> q2;
    animal cat = animal("cat");
    q2.push( cat );
    q2.pop();
    // 1st dtor call by pop()

    cout << "popd" << endl;
    // 2nd dtor call by cat


    return 0;
}


result

dog ctor : pochi
dog dtor : pochi
cat ctor : tama
cat dtor : tama
popd
cat dtor : tama


参考