Search code examples
c++qtstdshared-ptr

How to initialize a shared_ptr to a QTextCodec in my constructor?


I am trying to initialize a shared_ptr to a QTextCodec (Qt class for charset conversion) in my class constructor.

This is the code I have where I get a ‘virtual QTextCodec::~QTextCodec()’ is protected within this context error:

myencoder.h

#ifndef MYENCODER_H
#define MYENCODER_H

#include <memory>
#include <QTextCodec>

class MyEncoder
{
    std::shared_ptr<QTextCodec> m_codec;

public:
    MyEncoder(QString &aCodec);
};

#endif // MYENCODER_H

myencoder.cpp

#include "myencoder.h"

MyEncoder::MyEncoder(QString &aCodec)
{
    m_codec = std::shared_ptr<QTextCodec> (QTextCodec::codecForName(aCodec.toLatin1()));
}

How can I initialize my m_codec property in MyEncoder's constructor?


Solution

  • From docs:

    QTextCodec::~QTextCodec ( )     
                                  protected virtual
    

    Destroys the QTextCodec. You should not delete codecs. Once created their lifetime becomes the responsibility of CopperSpice.

    Same with the incorporated version:

    QTextCodec::~QTextCodec()               
                                 [virtual protected]
    

    Destroys the QTextCodec. Note that you should not delete codecs yourself: once created they become Qt's responsibility.

    So perhaps add empty deleter to your shared_ptr or use raw pointer and leave it up to library.