Passkey Idiom

조금 더 강력하게 클래스 접근을 제한하는 방법.


Passkey Idiom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Secure
{
int data;

public:
static std::shared_ptr<Secure> CreateSecureObj(int data);
class Key
{
friend std::shared_ptr<Secure> Secure::CreateSecureObj(int data);
Key() {};
};

explicit Secure(const Key& key, int data) : data{data} {};
};

std::shared_ptr<Secure> Secure::CreateSecureObj(int data)
{
return std::make_shared<Secure>(Secure::Key(), data);
}

Usage

1
2
3
auto pSecure1 = Secure::CreateSecureObj(10); // OK
auto pSecure2 = std::make_shared<Secure>(Secure::Key(), 10); // Error
auto pSecure3 = new Secure(Secure::Key(), 10) // Error



Easy way in c++11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <typename T>
class Key
{
friend T;
Key() {};
};

class Secure
{
int data;
public:
Secure(const Key<Secure>&, int data) : data{data} {};

static std::shared_ptr<Secure> CreateSecureObj(int data);
};

std::shared_ptr<Secure> Secure::CreateSecureObj(int data)
{
return std::make_shared<Secure>(Key<Secure>(), data);
}

Usage

1
2
3
auto pSecure1 = Secure::CreateSecureObj(10);  // OK
auto pSecure2 = std::make_shared<Secure>(Key<Secure>(), 10); // Error
auto pSecure3 = new Secure(Key<Secure>(), 10); // Error
Author

Joyus.Gim

Posted on

2022-04-17

Updated on

2022-07-19

Licensed under

Comments