在构造过程中应用type_id运算符
To apply type_id operator during the construction
代码:
#include <iostream>
#include <typeinfo>
#include <cassert>
using std::cout;
using std::endl;
long unsigned int hash_in_constructor;
struct A
{
virtual void foo()
{
cout << "A" << endl;
}
A()
{
hash_in_constructor = typeid(this).hash_code();
}
};
int main()
{
cout << hash_in_constructor << endl;
cout << typeid(A).hash_code();
}
演示
我预计hash_in_constructor
等于typeid(A).hash_code()
,因为12.7/5:
在构造函数中使用typeid时(包括mem初始值设定项或非静态数据成员的大括号或相等初始值设定项)或析构函数,或用于从构造函数或析构函数,如果typeid的操作数引用正在构建或销毁的对象,typeid会生成std::type_info对象,表示构造函数或析构函数的班
但事实并非如此。为什么?
有两个明显的问题:
-
仅当执行
A::A
时、当构造A的实例时才设置hash_in_constructor
。您在构造A的实例之前阅读了它,所以它还没有被设置(只是被静态初始化为零)。
-
你在比较
typeid(A)
和typeid(A*)
,它们是不同的。请记住,this
指针就是一个指针。
检查此版本代码的输出:
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
long unsigned int hash_in_constructor;
struct A {
virtual void foo() {
cout << "A" << endl;
}
A() {
hash_in_constructor = typeid(this).hash_code();
}
};
int main() {
cout << "static init = " << hash_in_constructor << endl;
A a;
a.foo();
cout << "after ctor = " << hash_in_constructor << endl;
cout << "typeid(&a) = " << typeid(&a).name() << " : " << typeid(&a).hash_code() << endl;
cout << "typeid(a) = " << typeid(a).name() << " : " << typeid(a).hash_code() << endl;
cout << "typeid(A) = " << typeid(A).name() << " : " << typeid(A).hash_code() << endl;
}
输出:
g++ -std=c++1y -Wall -Wextra -pedantic -pthread main.cpp -lcxxrt -ldl && ./a.out
static init = 0
A
after ctor = 15127845526165118748
typeid(&a) = P1A : 15127845526165118748
typeid(a) = 1A : 1295143305205299629
typeid(A) = 1A : 1295143305205299629
您必须使用typeid(*this)
而不是typeid(this)
,否则您将获得A*
的类型信息,这当然与A
不同。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 使用类型id运算符的最佳替代方法
- 具有重载<<运算符的简单模板类失败,"Invalid use of template-id"
- 运算符 [] 重载的"error: expected unqualified-id before 'float' "
- 为什么"A<0>=0"中的模板 id 由于大于或等于运算符">="而无法在没有空格的情况下编译?
- C++:运算符重载错误:"&"标记之前的预期非限定 id
- std::thread::id 中的分段错误::运算符==