问题描述
在单元测试库我提供了一个机制给一个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的名称是一个字符串。但是到prevent难以发现的错误,我觉得有义务满足不同用途,例如:
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_;
};
先不谈这个问题未能应对我preFER简单地将指针分配给这样的成员变量的构造内存分配失败的:
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.
请注意,它仍然有可能通过传递为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.
这篇关于我怎样才能prevent需要复制传递给AVR-GCC C ++的构造函数的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!