Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c++ - How should I manage my memory in cpp with calling a C-style interface?

I want to manage pointer with smart pointer in my code, however I must call old C-style interface to get pointer, like that:

void getPointer(T** pT, int* pSize);

Users pass an empty pointer of Pt and return a pointer, I want to manage it with smart pointer in my code like

std::shared_ptr<T> ptr;

How should I write my code? I have been told that use get() method is not a safe idea. Another question is, how should I safely copy memory stored in smart pointer to a raw pointer? (or vice)

question from:https://stackoverflow.com/questions/65842454/how-should-i-manage-my-memory-in-cpp-with-calling-a-c-style-interface

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can construct a std::shared_ptr<T> (or a std::shared_ptr<T[]>) from a T*. If the T(s) weren't allocated with new([]), you will need to provide the correct deallocation to the shared pointer.

Assuming that there is a void returnPointer(T* pT, int size); in that C interface.

struct C_interface_deleter {
    void operator()(T* ptr) { returnPointer(ptr, size); }
    int size;
};

void use_C_interface() {
    T* raw;
    int size;
    getPointer(&raw, &size);
    std::shared_ptr<T> ptr(raw, C_interface_deleter{ size });

    // stuff involving ptr
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...