我如何防止复制传递给avr-gcc C ++构造函数的字符串的需要? [英] How can I prevent the need to copy strings passed to a avr-gcc C++ constructor?

查看:325
本文介绍了我如何防止复制传递给avr-gcc C ++构造函数的字符串的需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

请注意,当名称实际上是动态分配时,仍然可以通过将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆