如何使用指向ojbects的共享指针向量
How to use a vector of shared pointers to ojbects
我正在尝试使用对象的共享指针向量。我在获取任何成员变量时都没有遇到任何问题,但当我尝试设置成员变量时,似乎什么都不起作用。我一定错过了什么,因为这似乎应该起作用。
#include <iostream>
#include <string>
#include <boost/random.hpp>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::string;
class vehicle{
public:
vehicle(){};
~vehicle(){};
virtual string getName(){
return this->name;
}
virtual string setName(string n){
this->name = n;
}
friend std::ostream& operator <<(std::ostream& outs, vehicle &v){
outs << v.getName();
return outs;
}
protected:
string name;
};
class car : public vehicle{
public:
car(){
this->name = "default name";
}
string setName(string n){
this->name = n;
}
string getName(){
return this->name;
}
};
typedef std::shared_ptr<vehicle> vehicle_ptr;
cout将打印字符串"默认名称",然后当我尝试更改名称时它将导致seg故障。
int main(){
std::vector<vehicle_ptr> vehicleLot;
vehicleLot.push_back(std::shared_ptr<car>(new car));
cout << vehicleLot[0]->getName() << endl;
vehicleLot[0]->setName("new name"); // this gives a seg fault
}
您的setName
方法当前的返回类型为std::string
,而不是void
。修复vehicle
和car
类中的签名。
到达期望返回类型而没有返回语句的函数的末尾是未定义的行为。最好为您选择的编译器打开适当的警告,因为大多数编译器都很容易发现这种情况。
代码中的错误是由setName
函数的错误定义引起的。看看它返回了什么:
virtual string setName(string n);
然而,您没有明确返回任何内容,我认为这会导致未定义的行为。
附带说明一下,您应该在这段代码中更频繁地使用const&
。
相关文章:
- 如何从具有移动语义的类对象中生成共享指针
- 使用共享指针的函数调用,其对象应为 const
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何访问由共享指针保存的类方法?
- 从矢量或地图中删除共享指针
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 使用共享指针实现复制 c'tor?
- 共享指针继承,而不先显式强制转换
- 如何检查类中共享指针的有效性?
- std::排序在共享指针的向量上
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 嵌套类、继承和C++中的共享指针
- 制作一对共享指针并推送一个向量
- 如何将共享指针用作函数参数
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 尝试通过共享指针使用变量时读取访问冲突
- 如何将元素插入到标准::地图的共享指针中?
- 共享指针生存期
- 初始化可变数据结构中的共享指针向量
- 阻止在返回时复制共享指针