c++ - 在成员变量中存储 std::to_string(x).c_str() 会产生垃圾

标签 c++ xcode

我有这个非常简单的 C++ 程序:

using namespace std;

class TheClass
{
private:
    const char *_numberString;

public:
    TheClass(int number)
    {
        _numberString = to_string(number).c_str();
    }

    operator const char *()
    {
        return _numberString;
    }
};

int main(int argc, const char * argv[])
{
   TheClass instance = 123;
   cout << (const char *)instance << endl;

   return 0;
}

当我在 Xcode 中运行它时,它会记录 \367\277_\377。但是,如果我将其更改为:

using namespace std;

class TheClass
{
public:   // Change 1/2
    const char *_numberString;

public:
    TheClass(int number)
    {
        _numberString = to_string(number).c_str();
    }

    operator const char *()
    {
        return _numberString;
    }
};

int main(int argc, const char * argv[])
{
    TheClass instance = 123;
    instance._numberString = to_string(123).c_str();   // Change 2/2
    cout << (const char *)instance << endl;

    return 0;
}

它会按应有的方式记录 123。我看不出我做错了什么。即使我将 123 更改为另一个数字,也会记录完全相同的内容。

最佳答案

此时

 _numberString = to_string(number).c_str();

您正在存储指向临时 std::string 值的驻留数据的指针,该值在该行代码之后无效。

访问 _numberString 有效地调用了未定义的行为。


如评论中所述,没有必要将 _numberString1 成员保留为 const char*。使用 std::string 成员代替:

class TheClass {
private:
     std::string  numberString_;

public:
    TheClass(int number) : numberString_(to_string(number)) {
    }

    operator const std::string& () {
         return numberString_;
    }
};

1) 您不应该为类成员名称使用前缀 _,这是为编译器和标准实现内在函数保留的。如果您不喜欢 m_ 等模式或其他前缀约定(例如我),只需使用后缀 _ 即可,如我的示例所示。

关于c++ - 在成员变量中存储 std::to_string(x).c_str() 会产生垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27256277/

相关文章:

c++ - 避免警告 : operation on ‘count’ may be undefined [-Wsequence-point]

ios - CMMotionActivityManager 无法检测到汽车模式

ios - 以编程方式访问 Assets 目录

ios - iOS 9 上的 Alamofire 1.3

c++ - 如何使用cmake链接库

c++ - 为什么通过基指针删除 [] 派生对象数组是未定义的行为?

c++ - 为什么 c++ 有单独的新和删除语法?

c++ - QT creator如何让一个UI生成的类继承其他类?

xcode - Xcode 9.2 中的 "Warning: unable to build chain to self-signed root for signer"警告

ios - 如何获取多个分段上传任务的上传进度