简体   繁体   中英

C++ String\ Vector initialization

I have questions about C++ initialization.

In Java: if I want a empty StringBuffer, I should use

StringBuffer sb = new StringBuffer();

to initialize a empty string buffer.

In C++: If I want to use a empty string, I can just declare

std::string str; 

or std::string str = "";

In real world projects should I always write like the second form?

How about declare an empty vectors?

vector<int> vec;

Is this OK? or should I give some null values to this vec?

std:string and std:vector are classes, not basic types: That mean that unlike an Integer which as a pseudo-random value at the declaration moment, string and vectors has a well defined initial value.

The default value for std::string is "".

The default content for std::vector is {}.

You may use what you prefer, but the initialization is not necessary, and even not very optimal.

  1. std::string str(""); It does a direct initialization and uses string(const char *) constructor.

  2. std::string str=""; It does a copy initialization.

  3. std::string str; It creates empty string.

Option 3 is just like others and less overhead. Use it Read more about the difference from here What's the motivation behind having copy and direct initialization behave differently?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM