使用auto
我可以创建私有类型的变量。例如,如果由于任何原因,我创建了一个返回私有类型对象的公共函数,我可以使用auto
接收该类型的变量:
class A
{
private:
struct B {};
public:
B& public_function_because_of_a_mistake();
};
A a;
auto& b = a.public_function_because_of_mistake();
// Perhaps, struct A::B is not properly design to support copying of elements.
// In the natural use of the class B (inside A), perhaps,
// there is no copy of objects of type B, so, the programmer didn't take
// the proper precautions.
decltype(b) b2 = b; // Unintended copy
// Perhaps the user wanted to call other function with same name, thinking 'b' was
// of another class.
b.something_unintended();
我知道这种情况(很多无意义的错误)是不太可能的,但是,无论如何,这不是一个“安全”或“设计”漏洞吗?因为C ++的主要焦点是通过严格的类型系统和访问控制规则来防止无意义的操作,auto
可以轻松地跳过它们。