dynamic-memory-allocation
全部标签 templatevoidcheckObject(TgenericObject){MyClassA*a=dynamic_cast(genericObject);if(a!=NULL){//weknowitisoftypeMyClassA}MyClassB*b=dynamic_cast(genericObject);if(b!=NULL){//weknowitisoftypeMyClassB}}这样的事情可能吗?我们有一个模板类型,但我们想知道它是实际类型吗? 最佳答案 在模板世界中,您可能只想为每种类型专门化模板,而不是进行运行时检查
tryblock中的new表达式在我的计算机中引发了bad_alloc异常。请注意,catch子句按值而不是按引用接收异常对象。为什么e.what()会打印出"badallocation"?我以为它会被切成薄片。#includeintmain(){try{int*p=newint[0x1F000000];}catch(std::exceptione){std::cout 最佳答案 VisualStudio(Dinkumware?)使用std::exception的实现,其中包含消息的内部存储†。(完成一个接受字符串的非标准构造函数。
为什么对f的调用没有解析为第一个函数重载?我收到错误:source.cpp:Infunction'intmain()':source.cpp:12:31:error:'A'isaninaccessiblebaseof'B'classA{};classB:A{};voidf(constA&){std::coutvoidf(T){std::cout(b));}请注意,如果我取出dynamic_cast,代码将起作用,但secondf被调用(它打印“Generic”)。但我想做的是接到第一个电话。我认为dynamic_cast会起作用,但由于某种原因它会导致问题。我在这里做错了什么?
为什么这段代码不起作用?std::shared_ptre=ep->pop();std::shared_ptrt;t=std::dynamic_pointer_cast(e);我收到以下错误:/usr/include/c++/4.6/bits/shared_ptr.h:386:error:cannotdynamic_cast'(&__r)->std::shared_ptr::.std::__shared_ptr::get[with_Tp=Event,__gnu_cxx::_Lock_policy_Lp=(__gnu_cxx::_Lock_policy)2u]()'(oftype'clas
我有一个基类和一个派生类。每个类都有一个.h文件和一个.cpp文件。我在下面的代码中将基类对象动态转换为派生类:h文件:classBase{public:Base();virtual~Base();};classDerived:publicBase{public:Derived(){};voidfoo();};classAnother{public:Another(){};voidbar(Base*pointerToBaseObject);};cpp文件:Base::Base(){//dosomething....}Base::~Base(){//dosomething....}voi
我的程序中出现了bad_alloc异常。这些是限制条件:1每个字符串的长度最多为100000,并且只包含小写字符。由于这些限制,我无法弄清楚为什么我的程序得到bad_alloc。#include#include#include#includeclassSuffixArray{std::vectorsuffixes;size_tN;public:SuffixArray(std::string&s){N=s.length();suffixes.resize(N);for(size_ti=0;i>T;std::vectorresults;for(inti=0;i>str;SuffixArra
这个在面试中被问到了。如何编写自己的dynamic_cast。我想,基于typeid的name函数。现在如何实现自己的typid?我对此一无所知。 最佳答案 你没有任何线索是有原因的,dynamic_cast和static_cast不像const_cast或reinterpret_cast,它们实际上执行指针运算并且在某种程度上是类型安全的。指针运算为了说明这一点,请考虑以下设计:structBase1{virtual~Base1();chara;};structBase2{virtual~Base2();charb;};struc
我看到一本关于C++的书提到使用静态转换在继承层次结构中导航比使用动态转换更有效。例子:#include#includeusingnamespacestd;classShape{public:virtual~Shape(){};};classCircle:publicShape{};classSquare:publicShape{};classOther{};intmain(){Circlec;Shape*s=&c;//Upcast:normalandOK//Moreexplicitbutunnecessary:s=static_cast(&c);//(Sinceupcastingis
我遇到了这个:structBase{void*operatornew(size_t);voidoperatordelete(void*);virtual~Base(){}//(p);if(dynamic_cast(pB)!=0){/*...NOTreachinghere?...*/}free(p);}现在如果我们这样做,Base*p=newDerived;deletep;令人惊讶的是,conditioninsidetheBase::deleteisnotsatisfied我做错了什么吗?或者从void*进行转换会丢失Derived*的信息? 最佳答案
在C中++Howtoprogram有一段说:Acommonprogrammingpracticeistoallocatedynamicmemory,assigntheaddressofthatmemorytoapointer,usethepointertomanipulatethememoryanddeallocatethememorywithdeletewhenthememoryisnolongerneeded.Ifanexceptionoccursaftersuccessfulmemoryallocationbutbeforethedeletestatementexecutes,a