gpt4 book ai didi

c++ - 使用自动类型推导时奇怪的 boost cpp_Int 行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:53 25 4
gpt4 key购买 nike

在使用 auto 存储 boost cpp_int 操作的结果时,我刚刚注意到一些非常奇怪的行为

#include <boost/multiprecision/cpp_int.hpp>

int main() {
using boost::multiprecision::cpp_int;
cpp_int a = 1, b = 10 * a, d;
auto c = 10 * a;
d = c;
std::cout << b << " " << c << " " << d << "\n";
}

哪些输出:

10 0 0 

代替:

10 10 10

谁能解释一下?

最佳答案

问题是 boost::multiprecision使用 expression templates试图避免计算中间结果(链接的 Boost 页面有一个部分解释了这样做的原因)。

因此,下面表达式中c的类型不是cpp_int

auto c = 10 * a;  // c is some internal implementation defined type

您可以通过 comparing the types of say a and c 确认这一点.

#include <boost/type_index.hpp>
std::cout << boost::typeindex::type_id_with_cvr<decltype(c)>().pretty_name();

Boost的介绍甚至特别提到使用auto存储表达式模板的陷阱

One other potential pitfall that's only possible in C++11: you should never store an expression template using:

 auto my_expression = a + b - c;

unless you're absolutely sure that the lifetimes of a, b and c will outlive that of my_expression.

在您的情况下,其中一个操作数是文字,这似乎会影响将表达式模板转换为 cpp_int 的结果,即使 c 的生命周期匹配一个。如果不深入研究 operator* 的实现,很难说到底发生了什么,但足以说明您正在做不应该做的事情,而且您的示例很可能具有未定义的行为。

您可以通过多种方式解决此问题,首先是使用 cpp_int 而不是 auto。或者将表达式模板的结果转换为cpp_int

auto c = cpp_int(10 * a);

或者将10存储在一个cpp_int中;那么 Boost 文档中提到的警告适用,您的示例会产生预期的结果。

cpp_int a = 1, b = 10 * a, d, e = 10;
auto c = e * a;

关于c++ - 使用自动类型推导时奇怪的 boost cpp_Int 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com