gpt4 book ai didi

c++ - 从函数返回一个包含另一个对象的对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:18 25 4
gpt4 key购买 nike

为什么第一次调用 cout 后 drawManifestoGlobal 中的值会发生变化?看起来 canvas.panel.drawManifestoGlobal 被破坏了 - 为什么?

我该如何解决这个问题?

#include <iostream>

class DrawManifestoGlobal {
public:
int value = 2;
};

class Panel {
public:
void setDrawManifestoGlobal(DrawManifestoGlobal & _drawManifestoGlobal);
DrawManifestoGlobal * drawManifestoGlobal;
};

class Canvas {
public:
Canvas() {};
Canvas(DrawManifestoGlobal _drawManifestoGlobal);
DrawManifestoGlobal drawManifestoGlobal;
Panel panel;
};


class SerDe {
public:
Canvas doSerDe();
};

Canvas SerDe::doSerDe() {

DrawManifestoGlobal drawManifestoGlobal;
drawManifestoGlobal.value = 99;
Canvas canvas(drawManifestoGlobal);

return canvas;
}

Canvas::Canvas(DrawManifestoGlobal _drawManifestoGlobal) {
drawManifestoGlobal = _drawManifestoGlobal;
panel.setDrawManifestoGlobal(drawManifestoGlobal);
}

void Panel::setDrawManifestoGlobal(DrawManifestoGlobal &_drawManifestoGlobal) {
drawManifestoGlobal = &_drawManifestoGlobal;
}

int main () {
SerDe serde;
Canvas canvas;
canvas = serde.doSerDe();

std::cout << canvas.panel.drawManifestoGlobal->value << std::endl; // prints 99
std::cout << canvas.panel.drawManifestoGlobal->value << std::endl; // prints 0 (!!!)
}

关于实现要求:Canvas 拥有 Panel 和 DrawManifestoGlobal,Panel 本身有指向 Canvas 的 DrawManifestoGlobal 的指针,因此 Canvas 对其发生的任何更改对 Panel 都是可见的。

最佳答案

Why does the value in drawManifestoGlobal change after the first time cout is called on it? It looks like canvas.panel.drawManifestoGlobal gets destructed - why?

doSerDe() 函数内的

drawManifesttoGlobal 是一个局部变量,在作用域结束时过期,但您正在设置指向它的指针(Panel::drawManifestoGlobal) 并将指针传递到函数外部(通过 canvas 的返回)。所以你有未定义的行为来访问一个已经被破坏的对象的值。编译器完全有权为同一对象打印两个不同的值。

如果您确实需要一个指针(您不需要),您将需要动态分配 drawManifestoGlobal(最好使用 unique_ptr)。

class Panel {
public:
void setDrawManifestoGlobal(std::unique_ptr<DrawManifestoGlobal> _drawManifestoGlobal);
std::unique_ptr<DrawManifestoGlobal> drawManifestoGlobal;
};

Canvas SerDe::doSerDe() {
std::unique_ptr<DrawManifestoGlobal> drawManifestoGlobal(make_unique<DrawManifesttoGlobal>());
drawManifestoGlobal.value = 99;
return {std::move(drawManifestoGlobal)};
}

void Panel::setDrawManifestoGlobal(std::unique_ptr<DrawManifestoGlobal> drawManifestoGlobal) {
drawManifestoGlobal = std::move(_drawManifestoGlobal);
}

事实上,您的代码中的任何地方都不需要指针!

关于c++ - 从函数返回一个包含另一个对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51451741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com