簡體   English   中英

通過智能指針調用另一個類的成員函數

[英]Calling another class` member functions via smart pointers

在我正在編寫的程序中,我有一個創建和處理某些線程的類。 構造之后,將為此實例提供另一個類的對象,線程將能夠調用該類的成員函數。

我已經將其與原始指針一起使用(只需替換智能指針即可),但是由於我可以訪問智能指針,因此我嘗試改為使用它們。 雖然沒有太大的進步。

某些搜索使我使用了shared_ptr ,所以這是我想要做的:

Obj.hpp

#pragma once

#include "Caller.hpp"

class Caller;

class Obj : std::enable_shared_from_this<Obj> {
public:
    Obj(Caller &c);

    void dothing();
};

Caller.hpp

#pragma once

#include <memory>

#include "Obj.hpp"

class Obj;

class Caller {
public:
    void set_obj(std::shared_ptr<Obj> o);

    std::shared_ptr<Obj> o;
};

main.cpp

#include <iostream>
#include <memory>

#include "Caller.hpp"
#include "Obj.hpp"

void Caller::set_obj(std::shared_ptr<Obj> o)
{
    this->o = o;
}

Obj::Obj(Caller &c)
{
    c.set_obj(shared_from_this());
}

void Obj::dothing()
{
    std::cout << "Success!\n";
}

int main()
{
    Caller c;
    auto obj = std::make_shared<Obj>(c);

    c.o->dothing();
}

運行這段代碼會導致拋出std::bad_weak_ptr ,但是我不明白為什么。 由於objshared_ptr ,因此對shared_from_this()的調用不應該有效嗎?

使用gcc 7.1.1g++ main.cpp一起gcc 7.1.1

shared_from_this在將其包裝在共享指針中后才有效。

在構建時,還沒有指向您的共享指針。 因此,直到構造函數完成后,您才能shared_from_this

解決這個問題的方法是古老的“虛擬構造函數”技巧。 1個

class Obj : std::enable_shared_from_this<Obj> {
  struct token {private: token(int){} friend class Obj;};
public:
  static std::shared_ptr<Obj> create( Caller& c );
  Obj(token) {}
};

inline std::shared_ptr<Obj> Obj::create( Caller& c ) {
  auto r = std::make_shared<Obj>(token{0});
  c.set_obj(r);
  return r;
}

然后在測試代碼中:

Caller c;
auto obj = Obj::create(c);

c.o->dothing();

現場例子


1個虛擬構造函數既不是虛擬也不是構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM