使用 GMP,在 mpz_roinit_n() 之后省略 mpz_clear() 吗?

发布于 2025-01-20 21:43:42 字数 1145 浏览 2 评论 0 原文

GMP库提供了包装C API的大型INT C API和C ++ API。通常,您可以通过执行

mpz_t integ;
mpz_init(integ);

(请参阅)。这样做时,稍后您必须使用 mpz_clear(integ); 释放内存。 C ++ API的 MPZ_CLASS 自动为您处理此DEADLOCATION。

现在,如果要根据现有内存初始化 mpz_t ,并且不想复制内存内容,则可以使用函数 mpz_roinit_n()(<(<) a href =“ https://gmplib.org/manual/integer-special-functions” rel =“ nofollow noreferrer”> 5.16 Integer Special Functions )用于 xp :

mpz_srcptr mpz_roinit_n(mpz_t x, const mp_limb_t *xp, mp_size_t xs)

这以特殊的方式初始化 x ,因此可以用作其他MPZ函数的纯输入操作数(因此,函数名称中的 ro )。现在, mpz_clear(integ)的文档说:

释放X所占用的空间。为所有MPZ_T调用此功能 变量与它们完成后。

我想知道 mpz_t 's是否已通过呼叫 mpz_roinit_n()来初始化,因为它们不需要对其进行交易。

如果我正确,这也意味着 mpz_roinit_n()无法与C ++ API的 mpz_class 一起使用,即使 mpz_class.get_mpz_t() ,因为 mpz_class 的destructor总是试图对基础 mpz_t 进行处理,这将导致内存问题。我在这里正确吗?

The GMP library provides a big int C API and a C++ API which wraps the C API. Usually you initialize an mpz_t struct (C API) by doing

mpz_t integ;
mpz_init(integ);

(see 5.1 Initialization Functions). When doing so, you later have to free the memory with mpz_clear(integ);. The C++ API's mpz_class handles this deallocation automatically for you.

Now, if you want to initialize an mpz_t based on existing memory, and you don't want to copy the memory contents, you can use the function mpz_roinit_n() (5.16 Integer Special Functions) for a memory area pointed to by xp:

mpz_srcptr mpz_roinit_n(mpz_t x, const mp_limb_t *xp, mp_size_t xs)

This initializes x in a special way so it can be used as a read-only input operand (hence the ro in the function name) to other mpz functions. Now, the documentation of mpz_clear(integ) says this:

Free the space occupied by x. Call this function for all mpz_t
variables when you are done with them.

I wonder if mpz_t's which have been initialized with a call to mpz_roinit_n() are an exemption to this rule, because they don't need to be deallocated.

If I'm correct, this would also mean that mpz_roinit_n() can't be used with the C++ API's mpz_class, not even with mpz_class.get_mpz_t(), because mpz_class's destructor always tries to deallocate the underlying mpz_t, and this would cause memory issues. Am I correct here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你怎么这么可爱啊 2025-01-27 21:43:42

mpz_clear 对使用 mpz_roinit_n 设置的 mpz_t 不执行任何操作。所以你不需要调用它,但如果它被调用它仍然是安全的。

mpz_clear does nothing on a mpz_t set with mpz_roinit_n. So you don't need to call it, but it is still safe if it gets called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文