Bia*_*sta 12 c++ typeid clang++
给出以下源代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
并编译它:
clang++ -std=c++14 -Wall -Wextra -Werror -Wpedantic -g -o test test.cpp
环境设置:
linux x86_64
clang version 5.0.0
Run Code Online (Sandbox Code Playgroud)
由于警告(注释-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();
Run Code Online (Sandbox Code Playgroud)
(请注意:海湾合作委员会并未声称存在这种潜在问题)
题
有没有办法获得有关a指向的类型的信息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';
}
Run Code Online (Sandbox Code Playgroud)