gpt4 book ai didi

c++ - 为什么不允许从字符数组进行 std::string 初始化?

转载 作者:行者123 更新时间:2023-12-03 21:19:36 24 4
gpt4 key购买 nike

在 C++ 中,您可以从 char *const char * 初始化一个 std::string 对象,这隐含地假设字符串将在指针后找到的第一个 NUL 字符处结束。

然而,在 C++ 中,字符串文字是数组,即使字符串文字包含嵌入的 NUL,也可以使用模板构造函数来获取正确的大小。例如,参见以下玩具实现:

#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>

struct String {
std::vector<char> data;
int size() const { return data.size(); }

template<typename T> String(const T s);

// Hack: the array will also possibly contain an ending NUL
// we don't want...
template<int N> String(const char (&s)[N])
: data(s, s+N-(N>0 && s[N-1]=='\0')) {}

// The non-const array removed as probably a lot of code
// builds strings into char arrays and the convert them
// implicitly to string objects.
//template<int N> String(char (&s)[N]) : data(s, s+N) {}
};

// (one tricky part is that you cannot just declare a constructor
// accepting a `const char *` because that would win over the template
// constructor... here I made that constructor a template too but I'm
// no template programming guru and may be there are better ways).
template<> String::String(const char *s) : data(s, s+strlen(s)) {}

int main(int argc, const char *argv[]) {
String s1 = "Hello\0world\n";
printf("Length s1 -> %i\n", s1.size());
const char *s2 = "Hello\0world\n";
printf("Length s2 -> %i\n", String(s2).size());
std::string s3 = "Hello\0world\n";
printf("std::string size = %i\n", int(s3.size()));
return 0;
}

是否有任何特定的技术原因导致标准未考虑此方法,而是嵌入 NUL 的字符串文字在用于初始化 std 时最终被截断: :string 对象?

最佳答案

C++14 为字符串文字引入了一个后缀,使它们成为 std::string 对象,因此主要用例不再相关。

#include <iostream>
#include <string>
using namespace std;
using namespace std::literals;

int main() {
string foo = "Hello\0world\n";
string bar = "Hello\0world\n"s;
cout << foo.size() << " " << bar.size() << endl; // 5 12
cout << foo << endl; // Hello
cout << bar << endl; // Helloworld
return 0;
}

关于c++ - 为什么不允许从字符数组进行 std::string 初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com