following problem: I want to build a function which returns me a Pointer to an derived object from an abstract class. I think, the memory is freed when the function is left because i get an alloc-error. But i can't give the object back, because the class is abstract. In the function i decide, which derived class the object will be have. How can I solve the problem? Any idea?

QgsSymbolV2* QGISFunc::ReadClassSymbolsXML(QString FeatureType, QXmlStreamReader &reader)
    {
        QgsMarkerSymbolV2* p_mlmSymbol=0;
        try
        {
            QgsLineSymbolV2 mllSymbol;
            QgsFillSymbolV2 mlfSymbol;
            QgsMarkerSymbolV2 mlmSymbol;
...
return &mlmSymbol; // alloc error
有帮助吗?

解决方案 2

Your problem has nothing to do with the class being abstract. You create an object on the stack and then return its address. That address though will no longer be valid after the function returns. If you really want to return a pointer and delegate ownership to the caller, why not create it on the heap with new? Don't forget to delete it though later when you are done with that object, or consider smart pointers as @AndyProwl suggests.

其他提示

You are returning the address of a variable with automatic storage. That object gets destroyed when the function returns. The solution is to allocate the object on the heap. I suggest using a smart pointer (unique_ptr or shared_ptr in combination with make_shared<>()) for that purpose and return the smart pointer.

std::shared_ptr<QgsSymbolV2> QGISFunc::ReadClassSymbolsXML(
    QString FeatureType, 
    QXmlStreamReader &reader
    )
{
    try
    {
        ...
        std::shared_ptr<QgsSymbolV2> spObj = make_shared<QgsMarkerSymbolV2>();
        ...
        return spObj;
    }
    ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top