Best strategy for manual memory management with smart pointers?

Is there a recommended strategy for working with external libraries that expect manual guided pointers. For example, a method that takes a pointer vector:

ALibraryFunc(std::vector<ALibraryData*> p);

so usually you create your vector with something like:

std::vector<ALibraryData*> myVec;
for(...)
{
    myVec.push_back(new ALibraryData(args));
}
//and then
ret = ALibraryFunc(myVec);
//and then
for(auto &a:myVec)
{
    delete a;
}
myVec.clear();

I would prefer to use smart pointers, but the library will not take them. This makes me wonder if something like this is more smelly than just doing it manually:

std::vector<std::unique_ptr<ALibraryData>> myVecUP;
std::vector<ALibraryData*> myVec;
for(...)
{
    myVecUP.push_back(std::make_unique<ALibraryData>(args));
    myVec.push_back(myVecUP.back().get());
}
//and then
ret = ALibraryFunc(myVec);
myVec.clear();
myVecUP.clear();

The second version seems safer in case of exceptions or errors, but it risks dangling pointers. Am I missing something here? What are you doing / will do?

+4
source share
2 answers

'scope exit':

//open scope block
{
    std::vector<ALibraryData*> myVec;
    ////////////////////////////////////////
    struct MyVecRAIICleaner{ 
      std::vector<ALibraryData*> * myVecPtr;
      ~MyVecRAIICleaner(){ 
        if (myVecPtr) {
         for(auto& a: *myVecPtr)
            delete a;
         myVecPtr->clear();
        }
       }
    } myRAIICleaner = {&myVec};
    ////////////////////////////////////////
   for(...)
   {
       myVec.push_back(new ALibraryData(args));
    }
    //and then
    ret = ALibraryFunc(myVec);

    /** You needn't below code. */
    ////and then 
    //for(auto &a:myVec)
    //{
    //    delete a;
    //}
    //myVec.clear();

}// end scope block 

EDIT:
, Wojtek Surowka catch try .

+3

, :

struct VecOwner {
 std::vector<ALibraryData*> vec;
 VecOwner(<some arguments>)
 {
     // fill the vector here
 }
 ~VecOwner()  
 {
   for(auto &a:vec)
     delete a;
   vec.clear();
 }
};

, .

+5