本文介绍了弱指针这构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是不可能通过从类的构造函数调用shared_from_this()获得一个shared_ptr,为对象尚未构造。难道但可能获得的weak_ptr从构造函数的对象吗?有些升压论坛帖子讨论了weak_from_raw()方法表明,它可能是可能的。

I understand it is not possible to obtain a shared_ptr by calling shared_from_this() from the constructor of a class, as the object is not yet constructed. Is it possible however to obtain a weak_ptr to the object from the constructor? Some boost forum posts discussing a "weak_from_raw()" method suggests that it may be possible.

编辑:升压形式讨论weak_from_raw http://lists.boost.org/boost-users/2010/08/61541.php

Boost form discussing weak_from_raw http://lists.boost.org/boost-users/2010/08/61541.php

推荐答案

我觉得你引用什么<一个href=\"http://groups.google.com/group/boost-list/browse_thread/thread/36d8e06194227408/5625f636b47fdb96?pli=1\">is这。这似乎没有被合并到升压版本(可能是错了)。

I think what you're referencing is this. Which seems not to have been merged to the boost release (may be wrong about that).

从:

常见问题解答

问:的对象可以在其构造函数创建了weak_ptr本身?

Q. Can an object create a weak_ptr to itself in its constructor?

一个。第一个的weak_ptr只能从创建一个shared_ptr,并在对象施工时间不shared_ptr的对象还不存在。即使你可以创建一个临时的shared_ptr这一点,它会走出去的范围在构造函数的结尾,所有的weak_ptr实例会立即失效。

A. No. A weak_ptr can only be created from a shared_ptr, and at object construction time no shared_ptr to the object exists yet. Even if you could create a temporary shared_ptr to this, it would go out of scope at the end of the constructor, and all weak_ptr instances would instantly expire.

的解决方案是使构造私有的,并提供一个工厂函数返回一个shared_ptr

The solution is to make the constructor private, and supply a factory function that returns a shared_ptr:

class X
{
private:

    X();

public:

    static shared_ptr<X> create()
    {
        shared_ptr<X> px(new X);
        // create weak pointers from px here
        return px;
    }
};

这篇关于弱指针这构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:20