hg_git hg_git - 1 year ago 54
C++ Question

resizing string members in constructor

I've to make sure the string members are of fixed size during construction. However they can increase their size after construction is done and later in the program, user chooses to add more text to it.

class A {
std::string name;
std::string desc;
int num;

A(int, std::string, std::string);

Now if I do this -

A(int n, std::string name, std::string d) :

I'll have to call
inside the constructor body. This means there exists full string lengths at some time during the construction. Let's say I want the initial size to be 5, and user passes 20 chars string, during the construction and before
, the string would contain 20 chars, right?

Now I was thinking along the lines of doing this -

A(int n, std::string name, std::string d) :
name = name;
desc = d;

But this would be same right?

Should I instead call
on passed parameters itself? Or is there any better way..

Answer Source

What about constructor like this:

A::A(int n, const std::string &name, const std::string &d) :
    n(n), name(name, 0, 5), d(d, 0, 5)

The strings are never copied in their full length. They are taken by reference and the copy is constructed using at most first 5 characters.

It uses the substring constructor (number 3).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download