构造函数变量设置失败?GetModel返回模型索引数异常问题
问题排查:GetModel()返回空索引的Model对象
嘿,作为编程初学者遇到这种问题太正常了,我来一步步帮你理清问题所在!
问题根源
你的Model类自定义了拷贝构造函数和赋值运算符重载,但这两个函数都是空实现——这直接导致所有Model对象的拷贝操作都不会复制indices容器,新对象的indices自然是空的!
具体场景分析
我们拆解代码里的关键拷贝操作:
- 在
main中你创建了带36个索引的Model对象,随后以值传递的方式传给Class的构造函数:Class cl(model);,这里会调用Model的拷贝构造函数生成临时参数对象; - 构造函数内执行
m_model = model;时,调用了空的赋值运算符,没有把参数的indices复制给m_model; - 最后调用
GetModel()返回m_model时,又一次触发空的拷贝构造,返回的新Model对象自然带着空的indices。
解决方案
有两种简单有效的解决方法:
方法一:删除自定义的拷贝构造和赋值运算符
C++编译器会自动为类生成默认的拷贝构造函数和赋值运算符,默认实现会逐个复制类的所有成员变量(包括你的indices容器)。你只需要把Model类里这两个空函数删掉即可:
class Model { public: Model(const std::vector<unsigned int>& indices) { this->indices = indices; } Model(){} std::vector<unsigned int> indices; // 移除以下两个空实现的函数 // Model(const Model& other) {} // void operator = (const Model& other) {} };
方法二:手动实现拷贝逻辑
如果你确实需要自定义这两个函数(比如后续要添加其他成员的拷贝逻辑),要在函数内手动复制indices:
class Model { public: Model(const std::vector<unsigned int>& indices) { this->indices = indices; } Model(){} std::vector<unsigned int> indices; Model(const Model& other) { // 复制other的indices到当前对象 this->indices = other.indices; } void operator = (const Model& other) { // 复制other的indices到当前对象 this->indices = other.indices; } };
额外优化建议
把Class构造函数的参数改成const引用,这样可以避免不必要的对象拷贝,提升程序效率,这也是C++里的实用好习惯:
Class(const Model& model){ m_model = model; std::cout << model.indices.size() << std::endl; //输出: 36 std::cout << m_model.indices.size() << std::endl; //输出: 36 }
这样修改后,cl.GetModel().indices.size()就会正确输出36啦!
内容的提问来源于stack exchange,提问作者Freddy C.
相关产品推荐
相关产品推荐

