如何使用指向ojbects的共享指针向量

How to use a vector of shared pointers to ojbects

本文关键字:共享 指针 向量 ojbects 何使用      更新时间:2023-10-16

我正在尝试使用对象的共享指针向量。我在获取任何成员变量时都没有遇到任何问题,但当我尝试设置成员变量时,似乎什么都不起作用。我一定错过了什么,因为这似乎应该起作用。

#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。修复vehiclecar类中的签名。

到达期望返回类型而没有返回语句的函数的末尾是未定义的行为。最好为您选择的编译器打开适当的警告,因为大多数编译器都很容易发现这种情况。

代码中的错误是由setName函数的错误定义引起的。看看它返回了什么:

virtual string setName(string n);

然而,您没有明确返回任何内容,我认为这会导致未定义的行为。

附带说明一下,您应该在这段代码中更频繁地使用const&