cpp_VD - 8BitsCoding/RobotMentor GitHub Wiki
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. */