C++ "oldstyle container ":指针/数组/新 - 可能误会?

C++ "oldstyle container ": pointer/ array/ new - possible missconception?

本文关键字:误会 数组 container 指针 C++ oldstyle      更新时间:2023-10-16

>我只是在玩,只是不明白为什么第一个版本有效而第二个版本失败?

using namespace std;
#include <iostream>
int main(){
int a,b;
double d{3035.4534536};
cout<<"Size of: int "<<sizeof (int)<<" double "<<sizeof (double)<<endl;
a=*((int*)&d);
b=((int*)&d)[1];
int dd[2]; //{a,b};
dd[0]=a; dd[1]=b;
cout<<"a: "<<a<<" |b: "<<b<<endl;
cout<<"d: "<<d<<" |: "<<*((double*)&dd)<<endl;
// int  size=sizeof(d)/sizeof(int)+1, *temp= new int[size],
// *f{(int*)(&d)}, *t{temp}, *s{t+size};
// while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
// cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
// delete[] temp;
int size=sizeof(d)/sizeof(int)+1, *temp= new int[size];
char *f{(char*)&d}, *t{(char*)temp}, *s{t+sizeof(d)};
while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
delete[] temp;
}

。我知道,"这正是有容器的原因",这纯粹是好奇,我只是想了解第二个有什么问题?

是否有我不知道的转换?
还是 new-语句返回的指针比指向第一个元素的纯指针更多?

a=*((int*)&d);

不正确。当你这样做 (int*( 时,你使用reinterpret_cast。

&d是一个指向双精度的指针。不能将指针转换为指向整数的指针。好吧,你可以,但你不能做下一个操作,取消引用它。一旦您尝试将内存点读取 by(int*)&d作为整数,您就会得到未定义的行为。

从那里发生的事情是复杂的和不确定的。不要去那里。