c++ - 标记为可能丢失 block 的静态指针是否损坏?

标签 c++ pointers valgrind

在阅读了有关 Valgrind 的“可能丢失” block 消息后,它们似乎很糟糕。

我收到静态指针类成员的错误。 我想验证我们的代码没有任何问题。

我从 Valgrind 得到这个:

==27986== 76 bytes in 1 blocks are possibly lost in loss record 370 of 1,143
==27986==    at 0x4C247F0: operator new(unsigned long) (vg_replace_malloc.c:319)
==27986==    by 0x107CFEE8: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (new_allocator.h:94)
==27986==    by 0xDDCE21F: char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) (basic_string.tcc:140)
==27986==    by 0x107D19B2: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (basic_string.h:1722)
==27986==    by 0xD381F19: MyNamespace::MyClass::MyMethod() (MyClass.cpp:189)
==27986==    by 0xD1A6E17: __static_initialization_and_destruction_0(int, int) (IProperty.cpp:520)
==27986==    by 0xD1B2B97: _GLOBAL__sub_I_IProperty.cpp (IProperty.cpp:551)
==27986==    by 0x400D4F2: call_init (in /lib64/ld-2.5.so)
==27986==    by 0x400D5B4: _dl_init (in /lib64/ld-2.5.so)
==27986==    by 0x4000AA9: ??? (in /lib64/ld-2.5.so)

此错误所指的我的类(class)(简体): 我已简化代码以将其发布到此处,但如果需要,我可以添加更多详细信息。

MyClass.h

class MyClass
{
   private:
     double _p1, _p2, _p3, _p4;
     std::string _p5, _p6, _p7;
   public:
      MyClass(double p1, double p2, double p3, double p4, std::string p5, std::string p6, std::string p7) 
      {
         _p1 = p1;
         _p2 = p2;
         _p3 = p3;
         _p4 = p4;
         this->_p5 = p5;
         this->_p6 = p6;
         this->_p7 = p7;
      }

      static  MyClass& MyMethod();

}

MyClass.cpp

    static MyClass* _myPtr = NULL;
    MyClass&  MyClass::MyMethod()
    {
        if (!_myPtr )
        {
            _myPtr  = new MyClass(1, 2.1, 3, 4, "xxxx", "yyyyy", "zzzzz");
        }
        return *_myPtr ;
    }

我认为我们正确地使用了静态指针。但是,文档说这通常是内存泄漏,除非您对指针做了一些有趣的事情。我不认为我们在做任何有趣的事情。

这个错误实际上是指构造函数作为参数接收的字符串类的内部指针吗?

我们应该担心这个可能丢失的 block 错误吗?

最佳答案

这是一个内存泄漏,并不重要,因为这个对象应该和程序本身一样长,但是永远不会调用 MyClass 的析构函数和释放指针。如果 MyClass 使用程序外部的某些资源可能会出现问题。

尝试

MyClass&  MyClass::MyMethod()
{
    static MyClass instance(1, 2.1, 3, 4, "xxxx", "yyyyy", "zzzzz");
    return instance;
}

将调用析构函数(当所有静态对象都将被销毁时 - 在退出 main 之后)。

在 C++11 中,它甚至被授予线程安全性。

关于c++ - 标记为可能丢失 block 的静态指针是否损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30306140/

相关文章:

c++ - 将有根层次结构的对象存储在 vector 中

c - 如何分配内存并用指向二维数组的指针填充结构

java - 无法将 boost::shared_ptr<> 传递给 NewObject()

c++ - 写入文本文件的数据部分损坏且无法恢复

c - 结构体的指针运算给出奇怪的结果

c++ - 单例模式析构函数 C++

c - strtok() 在 C99 中返回错误值?

c++ - 潜在的指针问题和地址未被堆叠、分配或(最近)释放

c++ - 如何将 boost::any 打印到流中?

c++ - 如何修复用作初始值设定项错误的数组?