警告表达副作用

Clang Warning on expression side effects

本文关键字:副作用 警告      更新时间:2023-10-16

给定以下源代码:

#include <memory>
#include <typeinfo>
struct Base {
  virtual ~Base();
};
struct Derived : Base { };
int main() {
  std::unique_ptr<Base> ptr_foo = std::make_unique<Derived>();
  typeid(*ptr_foo).name();
  return 0;
}

并用:

编译

clang++ -std=c++14 -Wall -Wextra -Werror -Wpedantic -g -o test test.cpp

环境设置:

linux x86_64
clang version 5.0.0

由于警告(注意-Werror):

error: expression with side effects will be evaluated
      despite being used as an operand to 'typeid'
      [-Werror,-Wpotentially-evaluated-expression]
  typeid(*ptr_foo).name();

(只有注意:GCC并不声称这种潜在的问题)


问题

是否有一种方法可以获取有关unique_ptr指向的类型的信息,而不会产生这种警告?

注意:我是不是谈论禁用-Wpotentially-evaluated-expression或避免-Werror

看起来以下值应该在没有警告的情况下起作用,并给出正确的结果

std::unique_ptr<Foo> ptr_foo = std::make_unique<Bar>();
if(ptr_foo.get()){
    auto& r = *ptr_foo.get();
    std::cout << typeid(r).name() << 'n';
}