如何防止需要复制传递给 avr-gcc C++ 构造函数的字符串? [英] How can I prevent the need to copy strings passed to a avr-gcc C++ constructor?
问题描述
在 ArduinoUnit 单元测试库中,我提供了一种为 TestSuite 命名的机制.库的用户可以编写以下内容:
In the ArduinoUnit unit testing library I have provided a mechanism for giving a TestSuite a name. A user of the library can write the following:
TestSuite suite("my test suite");
// ...
suite.run(); // Suite name is used here
这是预期的用法 - TestSuite 的名称是字符串文字.然而,为了防止难以发现的错误,我觉得有必要迎合不同的用法,例如:
This is the expected usage - the name of the TestSuite is a string literal. However to prevent hard-to-find bugs I feel obliged to cater for different usages, for example:
char* name = (char*) malloc(14);
strcpy(name, "my test suite");
TestSuite suite(name);
free(name);
// ...
suite.run(); // Suite name is used here
因此,我已经实现了这样的 TestSuite:
As such I have implemented TestSuite like this:
class TestSuite {
public:
TestSuite(const char* name) {
name_ = (char*) malloc(strlen(name) + 1);
strcpy(name_, name);
}
~TestSuite() {
free(name_);
}
private:
char* name_;
};
抛开无法在构造函数中处理内存分配失败的问题,我更愿意简单地将指针分配给这样的成员变量:
Putting aside the issue of failing to deal with memory allocation failures in the constructor I'd prefer to simply allocate the pointer to a member variable like this:
class TestSuite {
public:
TestSuite(const char* name) : name_(name) {
}
private:
const char* name_;
};
有什么方法可以更改接口以强制它正确"使用,以便我可以取消动态内存分配?
Is there any way I can change the interface to force it to be used 'correctly' so that I can do away with the dynamic memory allocation?
推荐答案
如果你提供两个重载的构造函数会怎样?
What if you provide two overloaded constructors?
TestSuite(const char* name) ...
TestSuite(char* name) ...
如果使用 const char*
调用,那么构造函数可以复制指针,假设字符串不会消失.如果使用 char*
调用,构造函数可以复制整个字符串.
If called with a const char*
, then the constructor could make a copy of the pointer, assuming that the string will not go away. If called with a char*
, the constructor could make a copy of the whole string.
请注意,当 name
实际上是动态分配的时,仍然可以通过将 const char*
传递给构造函数来破坏这种机制.但是,这可能足以满足您的目的.
Note that it is still possible to subvert this mechanism by passing a const char*
to the constructor when the name
is in fact dynamically allocated. However, this may be sufficient for your purposes.
我应该指出,我从未真正在 API 中看到过这种技术,这只是我在阅读您的问题时想到的一个想法.
I should note that I have never actually seen this technique used in an API, it was just a thought that occurred to me as I was reading your question.
这篇关于如何防止需要复制传递给 avr-gcc C++ 构造函数的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!