return pointer to data declared in function

前端 未结 11 1577
南旧
南旧 2020-12-17 21:11

I know this won\'T work because the variable x gets destroyed when the function returns:

int* myFunction()
{
    int x = 4; return &x;
}
<
11条回答
  •  感情败类
    2020-12-17 21:36

    C++ approach to avoid memory leaks. (at least when You ignore function output)

    std::auto_ptr myFunction() {
        std::auto_ptr result(new int(4));
        return result;
    }
    

    Then call it:

    std::auto_ptr myFunctionResult = myFunction();
    

    EDIT: As pointed out by Joel. std::auto_ptr has it's own drawbacks and generally should be avoided. Instead std::auto_ptr You could use boost::shared_ptr (std::tr1::shared_ptr).

    boost::shared_ptr myFunction() {
        boost::shared_ptr result(new int(5));
        return result;
    }
    

    or when use C++0x conforming compiler You can use std::unique_ptr.

    std::tr1::unique_ptr myFunction() {
        std::tr1::unique_ptr result(new int(5));
        return result;
    }
    

    The main difference is that:

    • shared_ptr allows multiple instances of shared_ptr pointing to the same RAW pointer. It uses reference counting mechanism to ensure that memory will not be freed as long as at least one instance of shared_ptr exist.

    • unique_ptr allows only one instance of it holding pointer but have true move semantic unlike auto_ptr.

提交回复
热议问题