我有一个 Visual Studio 2013 C++11 程序,我需要使用一个在数组中分配多个字符缓冲区的 API:
int main(int argc, char* argv[])
{
char* names[10] = {};
unsigned int count = _countof(names);
some_external_api_to_get_values(count, names, &count);
// do something with the names array...
for (unsigned int i = 0; i < count; ++i)
release_objects(names[i]);
return 0;
}
我希望对象在销毁时自动释放。所以我添加了这个类,但是我遗漏了一些允许编译器在这个类和它期望的 char** 类型之间进行转换的东西。
template<typename T>
class release_objects_on_destruction : private boost::noncopyable
{
public:
explicit release_objects_on_destruction(T* p) : p_(p) { };
release_objects_on_destruction() : p_(nullptr) { };
~release_objects_on_destruction() { if (p_) release_objects(p_); };
T** operator&() { return &p_; };
operator T*() const { return p_; };
operator const T*() const { return p_; };
private:
T* p_;
};
int main( int argc, char* argv[])
{
release_objects_on_destruction<char> names[10];
unsigned int count = _countof(names);
// error C2664: 'int some_external_api_to_get_values(unsigned int,char**,unsigned int*)' : cannot convert argument 2 from 'release_objects_on_destruction<char> [10]' to 'char**'
some_external_api_to_get_values(count, names, &count);
return 0;
}
我缺少什么转换运算符?
最佳答案
它不起作用,因为您的 API 处于错误的级别。您需要将 external_api 调用和 release_objects 调用封装到同一个对象中。这就是您当前的包装器失败的原因。
class api_wrapper {
static const object_count = 10;
std::array<char*, object_count> objects;
unsigned count = object_count;
public:
api_wrapper() {
some_external_api_to_get_values(count, objects.data(), &count);
}
// example accessors
char** data() { return objects.data(); }
unsigned count() { return count; }
api_wrapper(api_wrapper&& other)
: objects(other.objects), count(other.count)
{
other.count = 0;
}
api_wrapper(const api_wrapper&) = delete;
~api_wrapper() {
for (unsigned int i = 0; i < count; ++i)
release_objects(objects[i]);
}
};
关于c++ - 自动释放由外部 api 分配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136457/