Clang warning about side effects of expression

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

Setting up the environment:

 linux x86_64 clang version 5.0.0 

It does not compile due to a 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(); 

(Note only: GCC does not claim to be such a potential issue)


Question

Is there a way to get information about the type specified by unique_ptr without generating such a warning?

Note. I'm not talking about disabling -Wpotentially-evaluated-expression or avoiding -Werror .

+5
source share
2 answers

It seems that the following should work without warning and give the correct result for the 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'; } 
+3
source

std::unique_ptr<T> has an alias of type std::unique_ptr<T>::element_type for T Try the following:

 int main() { auto ptr_foo = std::make_unique<Foo>(); typeid(decltype(ptr_foo)::element_type).name(); return 0; } 
+2
source

Source: https://habr.com/ru/post/1272237/


All Articles