这个问题在这里已经有了答案:UnabletofreeconstpointersinC(12个答案)关闭8年前。将C++11代码连接到某些C回调,我必须传递constchar*const*,即字符串数组。这是我的代码的简化版本:intmain(int,char**){constintcnt=10;constchar*const*names=static_cast(malloc(sizeof(char*)*cnt));//...allocatingnames[0],etc.comingsoon...the_c_function(names);free(names);return0;}所以我
片段1:#includeusingnamespacestd;classC{public:C(){}C(constC&c){cout输出:调用的const复制构造函数片段2:#includeusingnamespacestd;classC{public:C(){}C(constC&c){cout输出:调用了非常量复制构造函数片段3:#includeusingnamespacestd;classC{public:C(){}C(constC&c){cout输出:错误:复制构造函数必须通过引用传递它的第一个参数我很困惑:对于片段2,为什么此处的非常量复制构造函数有效?为什么调用非const复制
我研究了一下,operator函数的格式是(returnvalue)operator[space]op(arguments){implementation}但是,在std::reference_wrapper实现中,有一个运算符重载函数声明为operatorT&()constnoexcept{return*_ptr;。这个运算符和T&operator()constnoexcept{return*_ptr;不同吗?}?.如果两者不同,那么第一个有什么用? 最佳答案 运算符T&()constnoexcept;是一个user-define
给定一个lambda:autof=[](constT&var){returnvar;};为什么f的返回类型是T(不是constT&)?这在标准中的什么位置? 最佳答案 重点是:使用auto进行返回类型推导采用模板类型推导规则。返回类型被声明为按值传递;这意味着用于推导的表达式的引用性和顶级cv限定符(即var)将被忽略。标准引述:关于auto:Iftheplaceholderistheautotype-specifier,thededucedtypeT'replacingTisdeterminedusingtherulesforte
我有这样的代码,但我一直收到此错误:Avalueoftype"constchar*"cannotbeusedtoinitializeanentityoftype"char*"这是怎么回事?我已经阅读了以下主题,但无法看到我的答案的任何结果,因为它们都是从char到char*或char*到char:Valuetypeconstcharcannotbeusedtoinitializeanentityoftypechar*Valueoftypechar*cannotbeusedtoinitializeanentityoftype"char"#include;usingnamespacestd
最初我开始尝试在声明时使用初始化列表初始化constchar*[3]的vectorvectorv={{"a","b","c"}};这给出了错误matrixmustbeinitializedwithabrace-enclosedinitializer我觉得可能是constchar*的缘故,虽然看起来很奇怪,改成了字符串vectorv={{"a","b","c"}};但是错误依然存在。我尝试了几种牙套组合都无济于事。是否真的可以在声明时使用初始化列表初始化此结构? 最佳答案 编译失败因为std::vectorrequiresitsTto
我通常在C/C++代码中使用C类型转换。我的问题是,在转换类型中添加“const”关键字对结果有什么意义吗?比如我可以想出几个场景:constmy_struct*func1(){my_struct*my_ptr=newmy_struct;//modifymembervariablesreturn(constmy_struct*)my_ptr;//returnmy_instance;}在这个函数中,函数构造了一个结构的新实例,并将其转换为一个常量指针,因此调用者将无法进一步修改其内部状态,除非删除它。“const”转换是必需的、推荐的还是根本不需要的,因为任一return语句都有效。在这
我有一个对象:mapcollection;我想调用map::find函数,但我的键值为const,如以下代码,无法编译:constA*a=whatever();collection.find(a);以下代码有效并执行与查找操作等效的操作:constA*a=whatever();map::iteratoriter;for(iter=collection.begin();iter!=collection.end();++iter)if(iter->first==a)break;//iternowcontainstheresultormap::end(justlikemap::find)但它
考虑以下片段:#includeclassC{public:C(){}constint&f(constint&x)const{//Error:cannotcastconstint*toint*constreturnmyMap.find(&x)->second;//Withaconst_castworks://returnmyMap.find(const_cast(&x))->second;}std::mapmyMap;};int_tmain(intargc,_TCHAR*argv[]){intx=0;Cc;c.f(x);return0;}f()中的错误是由map的find()的const
我认为“const-correctness”的概念定义得很好,但当我和其他人谈论它时,我们似乎对它的含义有不同的看法。有人说这是关于一个程序在尽可能多的地方都有“const”注释。其他人将程序定义为const-correct当且仅当在使用const注释的地方没有违反constness时(即,它是编译器为您检查的属性)。所以我想知道,这些函数中哪些是const正确的:structPerson{stringgetName1()const{return_name;}stringgetName2(){return_name;}stringgetName3()const{_name="John"