关于表达式副作用的 Clang 警告
Clang Warning on expression side effects
给定以下源代码:
#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
由于warning(注-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
。
看起来下面应该可以在没有警告的情况下工作,并为派生 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';
}
给定以下源代码:
#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
由于warning(注-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
。
看起来下面应该可以在没有警告的情况下工作,并为派生 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';
}