cpp_week_ptr - 8BitsCoding/RobotMentor GitHub Wiki
์ํ์ฐธ์กฐ์ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด๋ณด์.
- ์ฝํ ์ฐธ์กฐ๋ ์์ ํฌ์ธํฐ ํด์ ์ ์ํฅ์ ๋ฏธ์น์ง ์๋๋ค.
- ์ฝํ ์ฐธ์กฐ ์นด์ดํธ๋ ์ฝํ ์ฐธ์กฐ์ ์๋ฅผ ์ ์ฅํ๋ ๋ฐ ์ฌ์ฉ๋๋ค
- ์ฝํ ์ฐธ์กฐ๋ก ์ฐธ์กฐ๋๋ ๊ฐ์ฒด๋ ๊ฐํ ์ฐธ์กฐ ์นด์ดํธ๊ฐ 0์ด ๋ ๋ ์๋ฉธ๋๋ค.
- ์ํ ์ฐธ์กฐ ๋ฌธ์ ๋ฅผ ํด๊ฒฐ!
#include <memory>
#include "Person.h"
int main() {
std::shared_ptr<Person> owner = std::make_shared<Person>("Pope");
std::weak_ptr<Person> weakOwner = owner;
// strong ref 1, weak ref 1์ด ๋๋ค.
return 0;
}
#include <memory>
#include "Person.h"
int main() {
std::shared_ptr<Person> owner = std::make_shared<Person>("Pope");
std::weak_ptr<Person> weakOwner = owner;
std::shared_ptr<Person> lockedOwner = weakOwer.lock();
// ์ฌ์ฉ์์๋ shared_ptr๋ก ์ฌ์ฉํด์ผํ๊ณ lockํจ์๋ฅผ ์จ์ share_ptr๋ก ์ ๋ฌ
return 0;
}
์ด๋ ๊ฒ ์ฐ๋ ์ด์ ๋ ๋ฉํฐ ์ค๋ ๋ฉ ํ๊ฒฝ์์ weak_ptr๋ก ์ฐ๋ ์ค์ ๋ค๋ฅธ ์ค๋ ๋์์ ํด๋น ํฌ์ธํฐ๋ฅผ ์ง์๋ฒ๋ฆด๊น๋ด ์์ ์ฅ์น๋ฅผ ๋๋ ๊ฒ
#include <memory>
#include "Person.h"
int main() {
std::shared_ptr<Person> owner = std::make_shared<Person>("Pope");
std::weak_ptr<Person> weakOwner = owner;
auto ptr = weakOwner.lock();
if(ptr == nullptr)
{
// ์ด๋ฏธ ์ง์์ก์ผ๋ฉด ์ฌ๊ธฐ๋ก ๋ค์ค๊ฒ ์ง?
}
}
#include <memory>
#include "Person.h"
int main() {
std::shared_ptr<Person> owner = std::make_shared<Person>("Pope");
std::weak_ptr<Person> weakOwner = owner;
if(weakOwner.expired()) // false
#include <memory>
#include "Person.h"
int main() {
std::shared_ptr<Person> owner = std::make_shared<Person>("Pope");
std::weak_ptr<Person> weakOwner = owner;
owner = nullptr;
if(weakOwner.expired()) // true
// ๋ ์ค ํ๋๋ ์ฝํ์ฐธ์กฐ๋ฅผ ๊ฐ์
class Pet
{
public:
void SetPet(const std::shared_ptr<Pet>& pet);
// ...
private:
std::shared_ptr<Pet> mPet;
}
class Person
{
public:
void SetOwner(const std::shared_ptr<Person>& owner);
// ...
private:
std::weak_ptr<Person> mOwner;
}