使用 shared_from_this 返回的指针访问私有成员
Accessing private member using this pointer returned by shared_from_this
我有一个如下所示的实现:
class A : public std::enable_shared_from_this<A>
{
public:
A() {}
void dummy(std::string name);
private:
std::map<std::string, std::string> cache;
};
void
A::dummy(std::string name) {
auto shared_this = shared_from_this();
auto find =
[name, shared_this] () {
auto iter = shared_this->cache.find(name);
};
}
我不确定这条线是如何工作的:
auto iter = shared_this->cache.find(名称);
看起来我们正在尝试使用指向 class 的指针来访问私有成员,但我不确定它的工作方式是否不同。
这是如何工作的?
It looks like we are trying to access the private member using a pointer to the class but I'm not sure if it works differently.
是的,没错。由于 dummy()
是 A
的成员,它可以访问 A
的所有成员,包括私有成员。
A::dummy(std::string name)
是 class A
的成员。因此,在此函数中,您可以访问 A
的任何实例的所有 public
、protected
和 private
成员。以下是标准中的相关引述:
N4140 §11 [class.access]/1
A member of a class can be:
(1.1) — private; that is, its name can be used only by members and friends of the class in which it is declared.
(1.2) — protected; that is, its name can be used only by members and friends of the class in which it is
declared, by classes derived from that class, and by their friends (see 11.4).
(1.3) — public; that is, its name can be used anywhere without access restriction.
N4140 §11 [class.access]/2
A member of a class can also access all the names to which the class has access. A local class of a member function may access the same names that the member function itself may access.
我有一个如下所示的实现:
class A : public std::enable_shared_from_this<A>
{
public:
A() {}
void dummy(std::string name);
private:
std::map<std::string, std::string> cache;
};
void
A::dummy(std::string name) {
auto shared_this = shared_from_this();
auto find =
[name, shared_this] () {
auto iter = shared_this->cache.find(name);
};
}
我不确定这条线是如何工作的: auto iter = shared_this->cache.find(名称);
看起来我们正在尝试使用指向 class 的指针来访问私有成员,但我不确定它的工作方式是否不同。
这是如何工作的?
It looks like we are trying to access the private member using a pointer to the class but I'm not sure if it works differently.
是的,没错。由于 dummy()
是 A
的成员,它可以访问 A
的所有成员,包括私有成员。
A::dummy(std::string name)
是 class A
的成员。因此,在此函数中,您可以访问 A
的任何实例的所有 public
、protected
和 private
成员。以下是标准中的相关引述:
N4140 §11 [class.access]/1
A member of a class can be:
(1.1) — private; that is, its name can be used only by members and friends of the class in which it is declared.
(1.2) — protected; that is, its name can be used only by members and friends of the class in which it is declared, by classes derived from that class, and by their friends (see 11.4).
(1.3) — public; that is, its name can be used anywhere without access restriction.
N4140 §11 [class.access]/2
A member of a class can also access all the names to which the class has access. A local class of a member function may access the same names that the member function itself may access.