在 C 语言中,如果结构包含 futex 或出于任何原因复制或移动到新地址没有意义,是否有任何方法(类型注释或其他东西)来限制/警告用户意外复制这些对象?
问问题
72 次
2 回答
1
你可以用不透明类型和私有封装做类似的事情。
某事.h
typedef struct something something; // forward declaration, incomplete/opaque type
something* something_create (void);
void something_dostuff (something* obj);
某事.c
#include "something.h"
struct something { ... }; // actual definition, only visible privately in this file
something* something_create (void)
{
something* result = malloc( sizeof *result );
...
return result;
}
void something_dostuff (something* obj)
{
/* do stuff on the object */
}
调用者.c
#include "something.h"
something* st = something_create();
something_dostuff(st);
当然,这并不能阻止调用者故意进行肮脏的黑客攻击,例如memcpy
对指向的数据进行狂野的攻击。但是它阻止了一个理智的应用程序程序员错误地做事,这应该是这样做的目的。
于 2021-02-19T07:59:27.937 回答
-1
不是,没有。看起来你选择了错误的语言,试试 Rust、Go、Java、Python 等。虽然我猜它们中的一些(或全部)也不支持这个功能,但这是正确的方向。
正如评论所指出的,如果不希望让用户复制结构,则始终使用指针。
如果将结构信息提供给用户有问题,则可以在头文件中为用户替换具有相同大小的废话的结构成员,并自己保留真正的头文件,就像 WinAPI 所做的那样。然而,这会使一切变得复杂,因为类型大小、结构对齐等有时在不同的架构中是不同的。
于 2021-02-19T07:36:33.100 回答