c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题

标签 c++ class new-operator dynamic-memory-allocation

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

这是我的标题foo.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;
}

所以我假设对象指针 station 没有在 main 中分配内存。

最佳答案

stationinitialize_stations 中的局部变量,所以对它的任何更改都不会在函数之外产生影响。

一个直接的解决方法是让函数返回一个指向新数组的指针。

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

更好的解决方案是返回 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相应地。

关于c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221039/

相关文章:

c++ - 带有限定符的函数类型 typedef 的用例

python - 如何测试我的代码

c++ - 为什么在 C++ 中的类初始化之前使用作用域运算符 (::)?

c++ - C++中的新运算符

c++ - 如何耗尽内存?

JAVA:创建不干扰同一类其他对象的新对象

c++ - 如果两个规则匹配,如何让 Bison 使用规则?

c++ - 如何在 Windows 中使用与父进程相同的环境变量加上它自己的子进程?

c++ - C++0x 中的 "id"函数

C++11成员类初始化顺序