I have a library implemented in C++ which has a C interface. This C interface is
ID: 655579 • Letter: I
Question
I have a library implemented in C++ which has a C interface. This C interface is, for all intents and purposes, the only way to use this library. C++11 seems to discourage the use of raw pointers but neither shared_ptr or unique_ptr are suitable in this case. From what I understand, intrusive_ptr is an option, but I am both unsure of how this differs from maintaining my own ref count (I am new to C++) and wary of wading into boost yet (I am new to C++).
How should I handle memory management in C++11 and higher? I only state the spec to make it clear that I am willing to use the features of the latest spec and have no need to maintain compatibility with older specs.
Explanation / Answer
The fact that C++11 offers a range of smart-pointer classes to make life easier with memory management does not mean that you can't or shouldn't use raw pointers where that is appropriate.
The committee that maintains the C++ standard is very reluctant to remove existing features from the language and more so if it is a widely used and useful feature like raw pointers. Keeping the language backwards compatible is one of the corner stones in its evolution.
With that said, if you have to provide a C-compatible interface to your C++ library, you should use only features from the common subset of C and C++ in your interface and that means using raw pointers where they are visible in the interface and effectively letting the user of your library deal with allocation/deallocation (although you can provide functions for that).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.