c – 为引用分配引用是否为有效操作?
发布时间:2020-12-16 09:40:43 所属栏目:百科 来源:网络整理
导读:我有以下代码: void cStatisticDBSerializer::GetStats (std::map std::string,long long ioCounterStats,std::map std::string,long long ioGaugeStats,bool iSwitch){ // Before getting the stats,clear the containers ioCounterStats.clear (); ioGaug
我有以下代码:
void cStatisticDBSerializer::GetStats (std::map <std::string,long long >& ioCounterStats,std::map <std::string,long long >& ioGaugeStats,bool iSwitch) { // Before getting the stats,clear the containers ioCounterStats.clear (); ioGaugeStats.clear (); std::map <std::string,long long >& lStats = ioCounterStats; if (iSwitch) { lStats = ioGaugeStats; } // Do something with lStats } 问题是:将函数输入引用赋给局部变量lStats是否有效?由于某种原因,这编译得很好,但是没有按预期运行.但是,如果我将lStats更改为指针并按如下方式分配它(例如): std::map <std::string,long long >* lpStats = &ioCounterStats; 它工作得很好. 有人可以解释一下这里发生了什么.谢谢! 解决方法
创建后,您无法重新分配参考.相反,每次使用它都会“引用”原始作业.你的第一个例子相当于:
ioCounterStats /*lStats*/ = ioGaugeStats; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |