朋友功能的安全风险是什么

What are security risks with friend functions?

本文关键字:是什么 安全 功能 朋友      更新时间:2023-10-16

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。