c – 当我使用Boost UUID时,为什么我会从Valgrind获得未初始化的值警告?

我有一个成员班:

std::string mName;
boost::uuids::uuid mId;

在我写的构造函数中:

mName = boost::lexical_cast<std::string>(mId);

Valgrind写道:

==30714== Use of uninitialised value of size 8
==30714==    at 0x69E92FC: ??? (in /usr/lib/libstdc++.so.6.0.16)
==30714==    by 0x69E93EE: std::ostreambuf_iterator<char, std::char_traits<char> > std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_int<unsigned long>(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, unsigned long) const (in /usr/lib/libstdc++.so.6.0.16)
==30714==    by 0x69E9705: std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put(std::ostreambuf_iterator<char, std::char_traits<char> >, std::ios_base&, char, unsigned long) const (in /usr/lib/libstdc++.so.6.0.16)
==30714==    by 0x69F522C: std::ostream& std::ostream::_M_insert<unsigned long>(unsigned long) (in /usr/lib/libstdc++.so.6.0.16)
==30714==    by 0x6283A5: std::basic_ostream<char, std::char_traits<char> >& boost::uuids::operator<< <char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, boost::uuids::uuid const&) (uuid_io.hpp:55)
==30714==    by 0x62799D: bool boost::detail::lexical_stream_limited_src<char, std::char_traits<char>, true>::shl_input_streamable<boost::uuids::uuid const>(boost::uuids::uuid const&) (lexical_cast.hpp:1260)
==30714==    by 0x626DB4: bool boost::detail::lexical_stream_limited_src<char, std::char_traits<char>, true>::operator<< <boost::uuids::uuid>(boost::uuids::uuid const&) (lexical_cast.hpp:1431)
==30714==    by 0x6261EE: boost::detail::lexical_cast_do_cast<std::string, boost::uuids::uuid>::lexical_cast_impl(boost::uuids::uuid const&) (lexical_cast.hpp:1920)
==30714==    by 0x62590C: std::string boost::lexical_cast<std::string, boost::uuids::uuid>(boost::uuids::uuid const&) (lexical_cast.hpp:2087)
==30714==    by 0x624145: th::Object::Object(std::string const&) (Object.cpp:25)
t==30714== Conditional jump or move depends on uninitialised value(s)

会是什么呢?

最佳答案
boost :: uuids :: uuid是一个POD类型,因此默认初始化一个uuid对象实际上会使它保持未初始化状态.

确保在构造函数的初始化列表中初始化uuid对象:

class MyType
{
    std::string mName;
    boost::uuids::uuid mId;

public:
    MyType()
      : mName(), // not technically necessary since std::string has a
                 // non-trivial default constructor, but good for consistency
        mId() // necessary in order to actually initialize mId, remains
              // uninitialized otherwise
    {
        mName = boost::lexical_cast<std::string>(mId);
    }
};

或者更好的是,通过重新排序您的数据成员声明:

class MyType
{
    boost::uuids::uuid mId;
    std::string mName;

public:
    MyType()
      : mId(), // value-initialize mId
        mName(boost::lexical_cast<std::string>(mId)) // avoid unnecessary default
                                                     // construction of mName
    { }
};

转载注明原文:c – 当我使用Boost UUID时,为什么我会从Valgrind获得未初始化的值警告? - 代码日志