C++ 2D shared_ptr 数组用抽象多态类型初始化

C++ 2D shared_ptr array initialize with abstract polymorphic type

我有需要初始化二维数组的多态类型 就像 shared_ptr** 地图

这是我在没有 shared_ptr 时的初始化程序,你能告诉我有效的解决方案吗? 错误是不兼容的指针类型 shared_ptr** 和 Game_Object***

Map = new shared_ptr<Game_Object>();
    for (int i = 0; i < (int) width_; i++)
        Map[i] = new shared_ptr<Game_Object>();

Map = new shared_ptr<Game_Object>();shared_ptr<Game_Object>* 我需要得到这个“shared_ptr<Game_Object>**”我该怎么做?

i need to get this shared_ptr<Game_Object>** how i do that?

shared_ptr<Game_Object>** 是指向 Game_Object 共享指针的原始指针的原始指针。我不知道为什么你需要这么复杂和令人困惑的设置。但如果你想创建一个,你可以:

size_t x = 3, y = 4; // 3 x 4 2D array
std::shared_ptr<Game_Object> **arr = new std::shared_ptr<Game_Object>*[x]();
for (size_t i = 0; i < x; ++i)
    arr[i] = new std::shared_ptr<Game_Object>[y]();

当然你需要给那些共享指针赋值:

for (size_t i = 0; i < x; ++i)
    for (size_t j = 0; j < y; ++j)
        arr[i][j] = std::make_shared<Game_Object>(); 

完成后不要忘记 delete[] 分配内存

我同意一些程序员的观点。不如让容器为您管理分配业务。

此外,如果您 只是 在编译时知道行宽。

constexpr size_t const WIDTH = 200;

template<typename T, auto width>
using Arr2D_sptr = std::vector<std::array<std::shared_ptr<T>, width> >;

template<typename T>
auto make_row_sptr(size_t height) {
    return Arr2D_sptr<GameInvarient, WIDTH>{height};
}

int main()
{
    size_t height{100};
    auto my2d = make_row_sptr<GameInvarient>(height);
    // contagueous 2d of shared_ptr
    // and all pointed objects are already set 
    // from this point.
    // (objects are not contagueous)

    for (auto row : my2d) {
        for (auto sptr : row) {
            std::cout << sptr->x; // use object
        }
    }

    for (auto row = 0; row < height; ++row) {
        for (auto col = 0; col < WIDTH; ++col) {
            std::cout << my2d[row][col]->x; // use object
        }
    }

}

https://godbolt.org/g/czR3pZ