我是否需要初始化std :: string

时间:2018-05-17 15:41:04

标签: c++ c++11 initialization stdstring

我有这段代码:

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

当我编译并运行此代码时,出现o错误,在Windows中我总是得到str&#34;&#34;。

这总是有效吗?

我需要上述行为,如果用户没有调用set,str将始终是一个空字符串。

我应该在构造函数中初始化str,如下所示:

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

我想确保所有平台上的行为都相同,并确保代码尽可能小而整洁。

2 个答案:

答案 0 :(得分:4)

  

我是否需要初始化std :: string

没有。 std::string默认构造函数为您初始化一个漂亮的空字符串。

  

我想确保所有平台上的行为都相同,并确保代码尽可能小而且整洁。

然后删除杂乱:

struct myclass {
    std::string str;
};

Fundamental types但是,默认情况下不进行初始化,您需要明确初始化它们:

struct myclass {
    std::string str;
    int i = 1; // <--- initialize to 1.
};

答案 1 :(得分:0)

你不需要用空字符串初始化string成员,尽管它可以帮助你做任何事情。考虑:

struct foo {
    std::string a;
    std::string b;
    foo() : a("foo") {}
};

b是否意外或故意在构造函数中没有获得值?我更喜欢

foo() : a("foo"), b() {}

因为它使得意图明确无价(不计算几次击键)。