hg_git hg_git - 3 months ago 9
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;

public:
A(int, std::string, std::string);
.....
}


Now if I do this -

A(int n, std::string name, std::string d) :
num(n),
name(name),
desc(d)
{
....
}


I'll have to call
resize()
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
resize()
, 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) :
num(n)
{
name = name;
desc = d;
name.resize(5);
desc.resize(5);
....
}


But this would be same right?

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

Answer

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).