gpt4 book ai didi

c++ - 为什么显式模板实例化存在访问检查漏洞?

转载 作者:可可西里 更新时间:2023-11-01 15:26:11 26 4
gpt4 key购买 nike

[temp.explicit] 包含这样的措辞:

The usual access checking rules do not apply to names used to specify explicit instantiations. [Note: In particular, the template arguments and names used in the function declarator (including parameter types, return types and exception specifications) may be private types or objects which would normally not be accessible and the template may be a member template or member function which would not normally be accessible. —end note ]

为什么专门针对这种情况禁用了这些规则?在极端情况下,这允许 arbitrary access of any private member of any class以明确定义的方式(demo - 零警告):

struct A {
private:
int member;
};

template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};

// tag used to access A::member
struct A_member {
typedef int A::*type;
friend type get(A_member);
};

template struct Rob<A_member, &A::member>;

int main() {
A a;
a.*get(A_member()) = 42; // write 42 to it
std::cout << "proof: " << a.*get(A_member()) << std::endl;
}

这就是这条规则的缺点。有什么好处?为什么我们需要这个漏洞来避免访问检查?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com