我有以下情况:
但是,我遇到了一些内存问题,因为我的@Component({
selector: 'car-detail',
template: `
<h1>Car: {{car?.name}}</h1>
<hr>
<button (click)="addBrand()">Add Brand</button>
<div *ngIf="car">
<div *ngFor="let brand of car.getBrands(); let i=index">
<h2>Brand {{i+1}}</h2>
</div>
</div>
似乎在被发送到Dispatcher
之前被删除了。
伪代码看起来像这样:
Window
如何正确使用智能指针来解决此问题?
答案 0 :(得分:1)
我写了示例http://cpp.sh/8dkv7
正如您所看到的,您的代码是正确的:
#include <iostream>
#include <memory>
class Dispatcher;
class Window;
class Kernel
{
public:
std::shared_ptr<Window> window;
std::shared_ptr<Dispatcher> dispatcher;
};
class Window
{
public:
std::weak_ptr<Dispatcher> dispatcher;
};
class Dispatcher
{
};
int main()
{
Kernel k;
k.window = std::make_shared<Window>();
k.dispatcher = std::make_shared<Dispatcher>();
k.window->dispatcher = k.dispatcher;
if( auto dispatcher = k.window->dispatcher.lock() ) {
std::cout << "ok\n"; // i see ok, what about you?
}
}