Kor*_*rri 21 c++ constructor shared-ptr weak-ptr c++17
我有使用的成员函数(方法)
std::enable_shared_from_this::weak_from_this() 
简而言之:weak_from_this返回weak_ptr到这个。一个警告是它不能从构造函数中使用。如果有人使用继承的类的构造函数中的函数,则该函数weak_from_this将返回expired weak_ptr。我通过断言检查它是否未到期来进行防范,但这是运行时检查。
有没有一种方法可以在编译时进行检查?
Rei*_*ica 15
恐怕答案是“不,在编译时无法防止这种情况发生”。它总是很难证明一个消极的,但想想看:如果有可能保护功能这样的话,大概已经为完成weak_from_this和shared_from_this标准库本身。
No there is no way. Consider:
void call_me(struct widget*);
struct widget : std::enable_shared_from_this<widget> {
    widget() {
        call_me(this);
    }
    void display() {
        shared_from_this();
    }
};
// later:
void call_me(widget* w) {
    w->display(); // crash
}
The thing is there is a reason you want to check for not calling shared_from_this in the constructor. Think about that reason. It's not that shared_from_this cannot be called, it's because it's return value has no way of being assigned yet. It is also not because it will never be assigned. It's because it will be assigned later in the execution of the code. Order of operation is a runtime property of your program. You cannot assert at compile time for order of operation, which is done at runtime.