简体   繁体   中英

how to instantiate an object using smart pointers

Hi everyone I'm currently using QuickFast library and I saw this declaration using boost smart pointers:

namespace QuickFAST{
namespace Messages{
    class FieldIdentity;
    typedef boost::intrusive_ptr<const FieldIdentity> FieldIdentityCPtr;
    typedef boost::intrusive_ptr<FieldIdentity> FieldIdentityPtr;

    void QuickFAST_Export intrusive_ptr_add_ref(const FieldIdentity * ptr);
    void QuickFAST_Export intrusive_ptr_release(const FieldIdentity * ptr);
    void QuickFAST_Export intrusive_ptr_add_ref(FieldIdentity * ptr);
    void QuickFAST_Export intrusive_ptr_release(FieldIdentity * ptr);

    }
}

and I got another class which I need to instantiate, this is the class :

namespace QuickFAST{
namespace Messages{
    /// @brief the representation of a field within a message.
    class QuickFAST_Export MessageField
    {
    public:
    /// @brief Construct from an identity and a typed value.
        MessageField(const FieldIdentityCPtr & identity, const FieldCPtr & field)
            : identity_(identity)
            , field_(field)
            {
            }

    private:
        FieldIdentityCPtr identity_;
        FieldCPtr field_;
    };
    }
}

so my question is : when I need to create a MessageField, I need first to prepare my FieldIdentityCPtr (resp. FieldCPtr ) but it's a boost smart pointer, so correct me if I'm wrong but I thought maybe I can do this :

FieldIdentityCPtr identityFF_= new  FieldIdentity(nameFld,,idFld);
FieldCPtr fieldFF_ = new Field(typeFld,false);
MessageField(*identityFF_,*fieldFF_);

No , it should be MessageField(identityFF_,fieldFF_); .

When you dereference a smart pointer, you get back the original object. So if you do MessageField(*identityFF_,*fieldFF_); , you're basically passing a FieldIdentityC and a FieldC to the constructor, which in turn will try to convert them to smart pointers. So you'll have 2 different smart pointers referencing the same objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM