Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to initialize std::string

I have this code:

class myclass
{
    std::string str;
public:
    void setStr(std::string value)
    { 
        str=value;
    }
    std::string getStr()
    {
        return str;
    }
 }

 main()
 {
   myclass ms;
   std::cout<<ms.getStr()<<std::endl;
 }

when I compile and run this code, there is o error and in windows I am always getting str as "".

Is this always valid?

I need the above behavior in the fact that if user did not call set, str would be always a blank string.

should I initialize str in constructor as follow:

class myclass
{
    std::string str;
public:
    myclass():str(""){}
    void setStr(std::string value)
    { 
        str=value;
    }
    std::string getStr()
    {
        return str;
    }
 }

I want to make sure that behavior is the same on all platform and also make sure that code is as small and neat as possible.

like image 748
mans Avatar asked May 17 '18 15:05

mans


People also ask

Is it necessary to initialize string in C++?

The standard advice in c++ is always initialize all your variables. So yes, you should initialize it. That's just good practice.

Is std::string initialized to empty?

std::string::clear in C++The string content is set to an empty string, erasing any previous content and thus leaving its size at 0 characters.

How do you initialize a std::string in C++?

We'd like to initialise it. For example: class UserName { std::string mName; public: UserName(const std::string& str) : mName(str) { } }; As you can see a constructor is taking const std::string& str .

Why do I need std::string?

Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did. Save this answer.


1 Answers

Do I need to initialize std::string

No. std::string default constructor initialises a nice empty string for you.

I want to make sure that behavior is the same on all platform and also make sure that code is as small and neat as possible.

Remove clutter then:

struct myclass {
    std::string str;
};

Fundamental types though, do not get initialised by default, you need to initialize them explicitly:

struct myclass {
    std::string str;
    int i = 1; // <--- initialize to 1.
};
like image 55
Maxim Egorushkin Avatar answered Oct 27 '22 08:10

Maxim Egorushkin