如何避免 VS 中unique_ptr签入的性能警告

How to avoid performance warning for unique_ptr check in VS?

本文关键字:性能 警告 ptr 何避免 VS unique      更新时间:2023-10-16

此代码:

    unique_ptr<int> a;
    if (a) {
        cout << "ASSIGNED" << endl;
    }

甚至这个代码:

    unique_ptr<int> a;
    if (static_cast<bool>(a)) {
        cout << "ASSIGNED" << endl;
    }

导致此警告:

warning C4800: 'void (__cdecl *)(std::_Bool_struct<_Ty> &)' : forcing value to bool 'true' or 'false' (performance warning)
with
[
    _Ty=std::unique_ptr<int>
]

在 Visual Studio 2012 中的警告级别为 3。在第一条评论之后,我发现它仅在打开公共语言运行时支持/clr 时才会发生。我应该如何避免它?

if (a.get() != nullptr)

应该有效,但我认为这不是unique_ptr的设计方式,是吗?

您可以

直接使用

if (a != nullptr)

通常可以使用!!清除Visual Studio上的性能警告:

unique_ptr<int> a;
if (!!a) {
    cout << "ASSIGNED" << endl;
}

我很久以前在迈克尔霍华德的博客上读到过它,但我没有参考。他谈论的是干净的编译和使用编译器,而不是关闭警告。