shared_from_this与导致bad_weak_ptr的抽象类

时间:2019-06-24 19:32:31

标签: c++ c++11 pointers shared-ptr observer-pattern

我正在使用一个抽象类来定义一个观察者,从实现它的类中,我想使用诸如register(this)之类的东西来注册它,但是要使用共享指针,因此使用shared_from_this(),但是我得到bad_weak_ptr。

我了解到,我得到的异常是因为指针为空,我需要创建指针,但不确定如何运行,因为这是我尝试使用make shared的抽象类,但还算不上运气。 谢谢

Abstract-Observer.hpp

str1 = b'%PDF-'  # Begin PDF
str2 = b'%%EOF'  # End PDF

with open('oleObject1.bin', 'rb') as f:
    binary_data = f.read()
print(binary_data)

# Convert BYTE to BYTEARRAY
binary_byte_array = bytearray(binary_data)

# Find where PDF begins
result1 = binary_byte_array.find(str1)
print(result1)

# Remove all characters before PDF begins
del binary_byte_array[:result1]
print(binary_byte_array)

# Find where PDF ends
result2 = binary_byte_array.find(str2)
print(result2)

# Subtract the length of the array from the position of where PDF ends (add 5 for %%OEF characters)
# and delete that many characters from end of array
print(len(binary_byte_array))
to_remove = len(binary_byte_array) - (result2 + 5)
print(to_remove)

del binary_byte_array[-to_remove:]
print(binary_byte_array)

with open(os.path.expanduser('test1.pdf'), 'wb') as fout:
    fout.write(binary_byte_array)

Example.hpp

class Observer : public std::enable_shared_from_this<Observer>{
public:

virtual void update() = 0;

}

Example.cpp

class Example : public Observer {
public:
Example();
~ Example();

virtual void execute();
//From Observer
virtual void update() override;

Register.hpp

class Example::Example:{

}

Example: execute(){
***//Exception of weak_ptr here***

registerObserver(shared_from_this());

}

Example::update(){ 
//some code here
}

Register.cpp

class Register {
public:
Register();
~ Register();

virtual void registerObserver(shared_ptr<Observer> ) override;

}

我正在从另一个班级打电话

class Register::Register { 
}

Register:registerObserver(shared_ptr<Observer> observer ){
}

0 个答案:

没有答案