cpp_VD - 8BitsCoding/RobotMentor GitHub Wiki

Virtual destructor ํ™œ์šฉ

Virtual : ์ž๋…€ํด๋ž˜์Šค์—์„œ ์žฌ ์ •์˜ ๋˜์—ˆ์Œ์„ ์•Œ๋ฆฐ๋‹ค. ํ˜ธ์ถœ์‹œ ์ž๋…€ํด๋ž˜์Šค ํ•จ์ˆ˜๋„ ์žฌ ํ˜ธ์ถœ์ด ๋˜๋Š” ํšจ๊ณผ!

class Dog {
public:
    ~Dog() { cout << "Dog destroyed" << endl; }
};

class Yellowdog : public Dog {
public:
    ~Yellowdog() { cout << "Yellow dog destroyed." << endl; }
};

class DogFactory {
public:
    static Dog* createYellowDog() { return (new Yellowdog()); }
    // do others...
};

int main() {
    Dog* pd = DogFactory::createYellowDog();

    delete pd;
    // only Dog destructor Called!
    // ์šฐ๋ฆฌ๋Š” YellowDog destructor๋„ ํ˜ธ์ถœ์„ ์›ํ•œ๋‹ค.

    return 0;
}

ํ•ด๊ฒฐ์ฑ…1 -> virtual destructor

class Dog {
public:
    virtual ~Dog() { cout << "Dog destroyed" << endl; }
};

class Yellowdog : public Dog {
public:
    ~Yellowdog() { cout << "Yellow dog destroyed." << endl; }
};

class DogFactory {
public:
    static Dog* createYellowDog() { return (new Yellowdog()); }
    // do others...
};

int main() {
    Dog* pd = DogFactory::createYellowDog();

    delete pd;
    // YellowDog and Dog destructor Called!

    return 0;
}

ํ•ด๊ฒฐ์ฑ…2 -> shared_ptr

(์ฐธ๊ณ ) unique_ptr์€ ์˜ค์ง Dog๋งŒ ์„ ์–ธ์ด ๊ฐ€๋Šฅํ•˜๊ธฐ์— ์‚ฌ์šฉ์•ˆํ•จ.

class Dog {
public:
    ~Dog() { cout << "Dog destroyed" << endl; }
};

class Yellowdog : public Dog {
public:
    ~Yellowdog() { cout << "Yellow dog destroyed." << endl; }
};

class DogFactory {
public:
    static shared_ptr<Dog> createYellowDog() { return shared_ptr<Yellowdog>(new Yellowdog()); }
    // do others...
};

int main() {
    shared_ptr<Dog> pd = DogFactory::createYellowDog();

    // delete pd;
    // Shared_ptr(์Šค๋งˆํŠธํฌ์ธํ„ฐ)์€ ์ž๋™์œผ๋กœ ์†Œ๋ฉธ์ž ํ˜ธ์ถœ

    return 0;
}

/* All classes in STL have no virtual destructor, so be carefule inheriting from them. */

์ฐธ๊ณ ์‚ฌ์ดํŠธ
์œ ํˆฌ๋ธŒ

โš ๏ธ **GitHub.com Fallback** โš ๏ธ