简介(来自EricLippert博客):Vexingexceptionsaretheresultofunfortunatedesigndecisions.Vexingexceptionsarethrowninacompletelynon-exceptionalcircumstance,andthereforemustbecaughtandhandledallthetime.TheclassicexampleofavexingexceptionisInt32.Parse,whichthrowsifyougiveitastringthatcannotbeparsedasaninteger.
当我们执行以下操作时实际发生了什么:1)inti=-1;//32bitvoid*p;p=reinterpret_cast(i)在64位架构上,sizeof(void*)==82)longlongi;//64bitvoid*p=(unsignedint)(-1);i=retinterpret_cast(p)在32位架构上sizeof(void*)=4我大体上知道结果是什么,但我希望有人用C++标准来描述这个机制,以便更好地理解。在第二种情况下,行为类似于“积分促销”(4.5)中描述的行为(我将为-1)对于“int-unsignedlong”的情况,我们通常会说指针像有符号整数一样转换吗?
这个问题在这里已经有了答案:Downcastingusingthe'static_cast'inC++(3个答案)关闭8年前。我不明白为什么会这样。pReallyABase是一个向下转换的shared_pointer,它指向一个基类实例。我理解为什么编译器让我调用pReallyABase->onlyForDerived()因为我将它定义为派生类指针,但是当我尝试使用该指针调用派生类函数时为什么没有出现运行时错误?classBase{public:virtualstringwhatAmI(){return"IamaBase";}};classDerived:publicBase{publ
我正在编写与对齐相关的代码,如果给定的指针正确对齐,却没有标准的功能测试,这让我感到非常惊讶。似乎互联网上的大多数代码都使用(long)ptr或reinterpret_cast(ptr)测试对齐,我也使用了它们,但我想知道使用指向整数类型的强制转换指针是否符合标准。这里是否有任何系统触发断言?charch[2];assert(reinterpret_cast(reinterpret_cast(&ch[0])+1)==&ch[1]); 最佳答案 回答题目中的问题:没有。反例:在旧的Pr1me微型计算机上,一个普通指针是两个16位字。第
考虑以下代码#include#include#include#includestructBase{intx;Base(intx):x(x){}};structDerived:publicBase{inty,z;Derived(intx):Base(x),y(x+1),z(x+2){}};voidupdate(conststd::vector>&elements){for(constautoelem:elements){std::coutx>elements(4);{intctr=0;std::generate(begin(elements),end(elements),[&ctr]()
Paragraph4of[expr.cast](在撰写本文时可用的最新C++标准草案中)描述了C样式转换的行为如下:Theconversionsperformedbyaconst_cast,astatic_cast,astatic_castfollowedbyaconst_cast,areinterpret_cast,orareinterpret_castfollowedbyaconst_cast,canbeperformedusingthecastnotationofexplicittypeconversion.Thesamesemanticrestrictionsan
假设你有这样一个函数:SmartPtrdoSomething(SmartPtra);像这样的类:classA{}classB:publicA{}现在我这样做:SmartPtrfoo=newB();doSomething(foo);现在,我想取回一个SmartPtr来自doSomething的对象.SmartPtrb=doSomething(foo);这可能吗?我需要做什么样的选角?现在,我刚发现一些我认为丑陋的东西:B*b=(B*)doSomething().get()重要说明:我无权访问SmartPtr和doSomething()代码。 最佳答案
我有一个为我的项目设计的类层次结构,但我不确定如何实现它的一部分。这是类层次结构:classShape{};classColored{//Onlypurevirtualfunctions};classSquare:publicShape{};classCircle:publicShape{};classColoredSquare:publicSquare,publicColored{};classColoredCircle:publicCircle,publicColored{};在我的部分项目中,我有一个不同类型形状的std::vector。不过,为了运行算法,我需要将它们放在彩色对
这不是C++11我对微软的第三个参数感兴趣CMapStringToOb::GetNextAssoc,其定义如下:voidGetNextAssoc(POSITION&rNextPosition,CString&rKey,CObject*&rValue)const;然后我得到了以下用于测试的简单代码:两个好的案例和一个编译器错误的案例。classCMyObject:publicCObject//inordertouseCMapStringToOb{public:CMyObject(CStringname_):name(name_){}voidSayHello(){TRACE(_T("hel
据我所知(以及本主题:Whenshouldstatic_cast,dynamic_cast,const_castandreinterpret_castbeused?)const_cast是唯一应该能够消除变量常量性的强制转换。然而,当弄乱clang-6.0和g++5.4.0时,我偶然发现了一种与上述相矛盾的行为。看起来static_cast做的工作完全一样。这些主要函数在两个编译器中给出了完全相同的结果:测试类定义structBase{Base(){std::cout使用const_castintmain(void){std::cout(b).no_const();std::cout使