2

I want to pass a string with string.reserve(1000) and ensure that memory is allocated when I pass it into different structs. Is there a way to do this without explicitly doing it after every instantiation?

I want to avoid having to do this:

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);
}
0

2 Answers 2

3

You have to do it explicitly, compiler is not required to copy the capacity too when copying std::string.

You can add a constructor to do it for you.

struct Prefix{
  std::string path;
  Prefix(const string& p) : path(p) { path.reserve(p.capacity()); }
};
Sign up to request clarification or add additional context in comments.

2 Comments

What if the capacity is a variable? Would I have to use a class instead?
@user18764 What do you mean about capacity is a variable ?
0

If you don't need the origin string again, you should move rather than copy.

Prefix x = {std::move(path)};

This isn't technically guaranteed to preserve the capacity, but it's hard to imagine a sane implementation where it wouldn't work. (And no, SSO doesn't affect this, it just enforces a minimum capacity at all times).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.