C++ 通过引用传递时,结构成员变量的地址已更改
在EclipseCDT中调试我的模型(用C++编写)时遇到了一个问题。问题是,当我通过引用将包含各种成员变量(如字符串或向量)的结构变量传递给函数时,某些成员变量的值不会在该函数的范围内更新。详情如下:C++ 通过引用传递时,结构成员变量的地址已更改,c++,eclipse,debugging,c++11,C++,Eclipse,Debugging,C++11,在EclipseCDT中调试我的模型(用C++编写)时遇到了一个问题。问题是,当我通过引用将包含各种成员变量(如字符串或向量)的结构变量传递给函数时,某些成员变量的值不会在该函数的范围内更新。详情如下: struct ModelConfig { //... here are some other variables and constructors vector<int> crop_list; string path_to_input; //.... }; structmo
struct ModelConfig {
//... here are some other variables and constructors
vector<int> crop_list;
string path_to_input;
//....
};
structmodelconfig{
//…下面是一些其他变量和构造函数
矢量裁剪列表;
字符串路径_到_输入;
//....
};
假设现在我开始在GDB中调试,下面是第一个函数调用:
void modelMain::setupModel( const ModelConfig & sim_setting ){
//... some operations to configure the model using 'sim_setting'
/* 1.3 - Initialize the land */
Set_Environment(k_farm_land, sim_setting);
// breakpoint here, printing out the value of 'sim_etting' shows 'sim_setting.path_to_input = "data/"' ; Then I enter into 'Set_Environment' function ...
//...
}
void Set_Environment(vector<Soil> & farm_land, const ModelConfig & sim_setting) {
int EXP_ID = sim_setting.EXP_ID;
string strTmp_a;
strTmp_a = sim_setting.path_to_input + "soil/parameters.txt"; // Problem is here: the GDB shows here that sim_setting.path_to_input = " ". I am expecting strTmp_a = "data/soil/parameters.txt" which now is "soil/parameters.txt" ;
//... operations for reading data
}
void modelMain::setupModel(const ModelConfig和sim_设置){
//…使用“sim_设置”配置模型的一些操作
/*1.3-初始化土地*/
设置环境(农场、模拟设置);
//断点在这里,打印出'sim_etting'的值显示'sim_setting.path_to_input=“data/”;然后我进入'Set_Environment'功能。。。
//...
}
无效设置环境(矢量和农场、const ModelConfig和sim设置){
int EXP\u ID=sim\u setting.EXP\u ID;
字符串strTmp_a;
strTmp_a=sim_setting.path_to_input+“soil/parameters.txt”;//问题在于:GDB在这里显示sim_setting.path_to_input=“”。我希望strTmp_a=“data/soil/parameters.txt”现在是“soil/parameters.txt”;
//…读取数据的操作
}
sim\u setting.path\u to\u input
变量应包含名为data/
的字符串值,该值在调用setupModel(…)
期间是正确的,但在调用Set\u Environment(…)
期间该值丢失(或实际更改了地址)
在Eclipse中使用GDB debug跟踪变量的地址时,我注意到sim_setting
的地址在setupModel
和Set_Environment
中似乎都是正确的,但是path_to_input
和crop_list
的成员变量更改到了其他位置,从而导致数据丢失。使用.push\u back()
创建裁剪列表的值
我没有得到要点,因为我通过引用传递变量。我唯一能想象的是字符串和向量的赋值。有人对此有理论吗?提前非常感谢 “某些成员变量未更新”的确切含义是什么?是分配给strTmp_a
的任务给您带来了问题吗?@tobi303 thx,请立即回复!在“setupModel”的函数调用中,选择“sim_setting.path_to_input=“data/”,这是正确的。但当进入下一个函数“Set_Environment()”时,“sim_setting.path_to_input=”“”,这会导致“strTmp_a”“被分配了一个错误的路径字符串。@LiYu您是否重载了+运算符?由于您将sim_设置作为常量引用传递,因此不应允许您将sim_setting.path_更改为\u input。您显示的代码中没有显示您描述的行为。”。问题出在代码中的某个地方,您还没有显示。如果需要调试代码的帮助,则需要生成MCVE。