【问题标题】:Do I need to initialize std::string我需要初始化 std::string
【发布时间】:2018-05-17 15:41:03
【问题描述】:

我有这个代码:

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 作为 ""。

这总是有效的吗?

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

我是否应该在构造函数中初始化 str 如下:

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

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

【问题讨论】:

  • 需要初始化std::string --> 不需要
  • @liliscent 是行为保证吗?是否调用了字符串的构造函数?什么时候叫他们?
  • @drescherjm 谢谢,现在已修复。

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


【解决方案1】:

是否需要初始化 std::string

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

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

然后消除混乱:

struct myclass {
    std::string str;
};

Fundamental types 不过,默认情况下不要初始化,您需要显式初始化它们:

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

【讨论】:

【解决方案2】:

您不需要使用空字符串初始化string 成员,但无论如何它都可以帮助您。考虑:

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

b 在构造函数中没有得到值是偶然还是故意?我更喜欢

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

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

【讨论】:

  • foo() : a("foo"), b() {} 怎么样?
  • @NathanOliver 更好
猜你喜欢
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多