gpt4 book ai didi

c++ - 编译器如何隐式地进行这种转换?

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

我正在观看来自//build 的视频,其中 Herb Sutter 通过代码片段展示了显式转换关键字的好处:

template< /* ... */ > class unique_ptr {
public:
// ...
explicit operator bool() const { return get() != nullptr; }

他说用那个关键字,我们可以阻止它编译:

use(ptr * 42); // oops, meant *(ptr) * 42

实在是看不懂,showcase是怎么编译的?编译器如何进行转换?什么类型的?

最佳答案

它隐式地将 unique_ptr 转换为 bool,然后从 bool 转换为 int 以进行乘法运算。

(bool 转 int 表示 true 为 1,false 为 0)

关于c++ - 编译器如何隐式地进行这种转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458187/

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