Olaf wrote:
I wrap a legacy C library, e.g. the signature is
void set_error_buffer(char* buf);
where the buf length should be of length of 512 (it's defined).
Now I want to wrap it with std::string. What is the prefered way?
What do you expect to accomplish with 'std::string'? Apparently,
the API you're using is going to store the pointer to that buffer
and fill it in at some point in the future, without even asking
you about it. You simply cannot rely on them to be doing the same
thing to a 'std::string' object.
Of course, you could try defining a global 'std::string' object,
making sure it has at least 512 bytes and then passing the pointer
returned from its 'data()' member to that 'set_error_buffer', but
it's a BAD IDEA(tm). What I'd probably do:
class ErrorBufferWrapper {
char* buffer;
ErrorBufferWrapper(const ErrorBufferWrapper&);
ErrorBufferWrapper& operator=(const ErrorBufferWrapper&);
public:
ErrorBufferWrapper() : buffer(new char[512]) {
set_error_buffer(buffer);
}
~ErrorBufferWrapper() { delete[] buffer; }
std::string asString() const { return std::string(buffer); }
} const globalErrorBuffer; // notice the 'const'
...
// somewhere in your code
if (thereWasAnError)
std::cerr << globalErrorBuffer.asString() << std::endl;
...
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask