Search code examples
c++visual-studio-2010bstr

How to delete the variables with types BSTR in C++


The code below is mine structure and class containing the structure reference.

typedef struct MESSAGE
{
    int MessageType;
     BSTR Name;
    _bstr_t TimeStampIs;
} MESSAGE, *PMESSAGE;

typedef struct MESSAGENODE
{
    PMESSAGE Message;
    MESSAGENODE* pNext;
} MESSAGENODE, *PMESSAGENODE;


class Message
{
private:
    PMESSAGENODE        MessageQueueFront;
    PMESSAGENODE        MessageQueueBack;
public:
    bool AddMessageToQueue(PMESSAGE Message);
    void DeleteMessageQueue(void){
    PMESSAGE pMess;
    while((pMess = GetMachineMessage()) != NULL)
    {
        if((pMess->DialysisDataIs))
        SysFreeString(pMess->Name.Detach());
        delete pMess;
}
}m;

int main()
{
PMESSAGE Message;
    Message = new MESSAGE;
    Message->Name=L"ABC";
    Message->TimeStampIs=L"25252";
    m.AddMessageToQueue(Message);
    m.DeleteMessageQueue();
    return 0;
}

When i compile the above code i am getting the following errors in DeleteMessageQueue function

error C2451: conditional expression of type '_bstr_t' is illegal error C2228: left of '.Detach' must have class/struct/union


Solution

  • A couple of things, first the meat of your error

    SysFreeString(pMess->Name.Detach());
    

    Message::Name is a raw BSTR pointer, which I assure you does not have a member function called Detach(). The _bstr_t class, however, does. Change your struct to:

    typedef struct MESSAGE
    {
        int MessageType;
        _bstr_t Name;
        _bstr_t TimeStampIs;
    } MESSAGE, *PMESSAGE;
    

    Once done, you can remove the SysFreeString() call entirely, since now both Name and TimeStampIs are smart pointers and will auto-free on object destruction.