检索函数内用 operator new 分配的 class 指针 object 成员的值的问题

problems with retrieving the value of a class pointer object member allocated with operator new inside a function

我在使用以下代码时遇到问题。我尝试在函数中填充一个名为 station 的 object 成员,但我无法在 main().

中检索它

这是我的headerfoo.h

class DirectoryProperties
{
public:
    size_t      numberOfFolders;

    void        initialize_stations( StationBase *station );

private:
    void        fill_station_names( StationBase *station );
};

class StationInfo
{
public:
    std::string     name;
};

这是我的 foo.cpp

#include "foo.h"

void DirectoryProperties::fill_station_names( StationBase *station )
{
    station[0].name = "dummy";
}

void DirectoryProperties::initialize_stations( StationBase *station )
{
    size_t N = 1;

    station = new StationBase[ N ];

    this->fill_station_names( station );

    // this works
    std::cout << station[0].stationName << std::endl;
}

int main()
{
    DirectoryProperties dirInfo;

    StationBase *station = NULL;

    dirInfo.initialize_stations( station );

    // breaks here
    std::cout << station[0].stationName << std::endl;

    return 0;
}

所以,我可以在 DirectoryProperties::initialize_stations( StationBase *station ) 中正确地打印 station[0].name,但在 main() 中不行。

如果我尝试它也会中断

int main()
{
    DirectoryProperties dirInfo;

    StationBase *station = NULL;

    dirInfo.initialize_stations( station );

    // breaks here
    station[0].stationName = "dummy";

    return 0;
}

所以我假设 object 指针 stationmain 中没有分配内存。

stationinitialize_stations 中的局部变量,因此对它的任何更改都不会影响函数外部。

一个直接的解决方法是让函数 return 成为指向新数组的指针。

StationBase* DirectoryProperties::initialize_stations(  )
{
  ....
  StationBase* station = new StationBase[ N ];
  ....
  return station;
}

更好的解决方案是 return 和 std::vector<StationBase>。或者只是一个 StationBase,因为无论如何你只分配一个对象。

std::vector<stationBase> DirectoryProperties::initialize_stations()
{
    size_t N = 1;
    std::vector<stationBase> station(N);
    fill_station_names( station );
    return station;
}

并相应地修正 fill_station_names