Ciclomatic依赖和共享和弱指针

时间:2016-06-04 10:28:24

标签: c++ smart-pointers

我有以下情况:

enter image description here

但是,我遇到了一些内存问题,因为我的@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

如何正确使用智能指针来解决此问题?

1 个答案:

答案 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?
    }
  }