gpt4 book ai didi

c++ - 使用具有 string.reserve() 的字符串实例化结构

转载 作者:搜寻专家 更新时间:2023-10-31 01:28:53 26 4
gpt4 key购买 nike

我想用 string.reserve(1000) 传递一个字符串,并确保在我将它传递给不同的结构时分配内存。有没有办法在每次实例化后不显式地执行此操作?

我想避免这样做:

struct Prefix{
std::string path;
};

int main() {
std::string path = "hel";
path.reserve(1000);
std::cout << path.capacity() << "\n"; // 1000

Prefix x = {path};
std::cout << x.path.capacity() << "\n"; // 15
x.path.reserve(1000);
x.path += somestring;
Prefix y = {x.path};
std::cout << y.path.capacity() << "\n"; // 15
y.reserve(1000);
}

最佳答案

你必须明确地这样做,编译器在复制 std::string 时不需要复制容量。

您可以添加一个构造函数来为您完成。

struct Prefix{
std::string path;
Prefix(const string& p) : path(p) { path.reserve(p.capacity()); }
};

关于c++ - 使用具有 string.reserve() 的字符串实例化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50980269/

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