简体   繁体   中英

Clang Warning on expression side effects

Given the following source code:

#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;
}

and compiled it with:

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

Enviroment setup:

linux x86_64
clang version 5.0.0

It does not compile because of warning (note -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();

(Just a note: GCC does not claim that kind of potential problematic)


Question

Is there a way to get the information about the type pointed by a unique_ptr without generating that kind of warning?

Note: I am not talking about disabling -Wpotentially-evaluated-expression or avoiding -Werror .

Looks like following should work without warnings and give correct result for derived class

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM