朋友功能的安全风险是什么
What are security risks with friend functions?
friend函数有哪些安全风险?它会损害C++中的封装和数据隐藏吗?
尽管做了很多研究,我还是无法得到正确的答案。有人能举例给出一个具体的答案吗?
这里有一个例子,函数FUNC会破坏对多线程环境中数据的保护。
# include <windows.h>
# include <iostream>
using namespace std;
void func();
class DataAdapter
{
friend void func();
private:
static volatile LONG _index;
public:
static void incr()
{
InterlockedIncrement(&_index);
}
};
void func()
{
DataAdapter::_index += 1;
}
DWORD WINAPI threadproc(void *pdata)
{
pdata = pdata;
DataAdapter::incr();
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread = CreateThread(NULL , 0 , threadproc , 0 , 0 , 0);
WaitForSingleObject(hThread , 5000);
return 0;
}
朋友没有特别的安全风险功能。Friend函数是班级,就像班级成员一样;函数是否成员或朋友对安全风险(或其他任何风险)。
重要的是要记住封装和安全性是两回事。
friend
是C++语言的一个特性,它是数据隐藏的一种"例外"。
它与安全性无关,因为friend
只存在于语言级别,而不存在于涉及安全问题的运行时。
我代表@mankrase 回答
总是可以合法访问任何对象的私人成员。此外,如果您的代码包含未定义的行为,那么任何事情都可能发生(无论是否存在友元函数)。Friend functions
不代表安全风险;它们在安全性方面是中立的(在最好的情况下,对安全性是有益的,因为它们可以使代码更简单、更好地封装)。
谢谢Mankrase。
相关文章:
- 将传入的网络"char*"数据转换为"uint8_t"并返回的安全方法是什么?
- 在 c++ 中从执行的 shell 命令获取返回状态的安全方法是什么?
- 什么时候关闭__strict_ansi__标志是不安全的
- 在转换为较小的数值类型之前执行范围检查的安全、跨平台方法是什么
- 在插入时同时迭代一个映射,这在什么方面是不安全的
- Qt:写这个类的析构函数的正确和安全的方法是什么
- 在C++中动态分配向量的安全方法是什么
- 对我来说,使 boost::statechart::state_machine 线程安全的最简单方法是什么?
- 将长整数转换为字符数组的最安全方法是什么
- 向量::插入的异常安全保证是什么?
- 是什么使单例线程不安全
- 保留 std::initializer_list 的副本是否安全?理由是什么
- 蜘蛛猴是线程安全的是什么意思
- 线程安全数据结构类的用途是什么
- 验证加载的DLL是否具有有效证书的最安全方法是什么
- c++:跨平台且安全的系统(…)的替代方案是什么?
- 实现树形结构最安全的方法是什么?
- 标准库中自赋值不安全的move赋值操作符的基本原理是什么?
- 在需要void*参数的函数中传递unique_ptr最安全的方法是什么?
- 安全断开asio SSL套接字的正确方法是什么?