我在使用Microsoft Visual C++ 2015时遇到了一些困难,并且能够通过一个小程序复制该问题.鉴于以下课程:
class BaseClass {
public:
BaseClass()
: mValue( 0 )
, mDirty( true )
{}
virtual ~BaseClass() {}
virtual int getValue() const { if( mDirty ) updateValue(); return mValue; }
protected:
virtual void updateValue() const = 0;
mutable bool mDirty;
mutable int mValue;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
protected:
void updateValue() const override
{
mValue++;
mDirty = false;
}
};
class Impersonator {
public:
Impersonator() {}
// conversion operator
operator DerivedClass() const …Run Code Online (Sandbox Code Playgroud) C++专家的问题.
我们都知道在类构造函数中调用shared_from_this()会导致bad_weak_ptr异常,因为还没有创建实例的shared_ptr.
作为解决方法,我提出了这个诀窍:
class MyClass : public std::enable_shared_from_this<MyClass>
{
public:
MyClass() {}
MyClass( const MyClass& parent )
{
// Create a temporary shared pointer with a null-deleter
// to prevent the instance from being destroyed when it
// goes out of scope:
auto ptr = std::shared_ptr<MyClass>( this, [](MyClass*){} );
// We can now call shared_from_this() in the constructor:
parent->addChild( shared_from_this() );
}
virtual ~MyClass() {}
};
Run Code Online (Sandbox Code Playgroud)
有人认为这不安全,因为该对象尚未完全形成.他是对的吗?
我没有使用'this'来访问成员变量或函数.此外,只要我使用了初始化列表,所有成员变量都已初始化.我不知道这招可能不安全.
编辑:事实证明这个技巧确实会造成不必要的副作用.在shared_from_this()将指向临时shared_ptr,如果你不小心,在我的示例代码中的父子关系将打破.执行enable_shared_from_this()只是不允许它.谢谢,Sehe,指出我正确的方向.