c++ 避免将字符串文本复制到不会更改的类字符串数据成员

alen0pnh  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(112)

考虑以下类:

class Foo {
public:
  // Other constructors...

  Foo(const char* s) : bar{s} {}
  Foo(std::string_view s) : bar{s} {}
  Foo(std::string&& s) : bar{std::move(s)} {}
private:
  std::string bar;  // only changes upon Foo being moved from
  // other functions and data members...
};

字符串
定义的构造函数会用Foo("a string literal")将字符串字面量复制到bar。当给定字符串字面量时,有没有方法避免复制?
我想实现的是Foo在其构造函数中接受一个字符串。之后,它只需要读取该字符串。同时,该字符串必须比Foo存在。有没有一种方法可以做到这一点,而不会在Foo中复制该字符串?
一个想法是使用一个变体:

class Foo {
public:
  // Other constructors...

  Foo(const char* s) : bar{s} {}
  Foo(std::string_view s) : bar{std::string{s}} {}
  Foo(std::string&& s) : bar{std::move(s)} {}

private:
  std::variant<std::string, const char*> bar;
  // Other functions and data members...


然而,第一个构造函数仍然不能区分短寿命的字符数组和长寿命的字符数组,比如字符串字面量。我知道可以在构造函数中使用一个标签来区分这两种情况。虽然我对这个想法持开放态度,但担心的是,当使用错误的标签时,编译器不会发出警告。
有没有办法避免复制这个字符串?

cfh9epnr

cfh9epnr1#

您可以使用UDL操作符(某种程度上)重载字面量

struct literal_string {
    const char *v;
    literal_string(const char *p): v(p) {}
};
constexpr literal_string operator””_l(const char *p) {return p;}

字符串
添加构造函数

Foo(literal_string)


现在,您可以(基本上)使用Foo(“a string”_l)重载文字
编辑:
为了在不使用不必要的cookie的情况下解决生存期管理问题,我将在Foo中使用std::string_view,并为临时文件分配单独的std::string

auto f1 = Foo(“a string”_l);

std::string foo_string = tempStr();
auto f2 = Foo(foo_string);

相关问题