5

メンバーのいるクラスがあります。

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)

どうなり得るか?

4

1 に答える 1

9

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
    { }
};
于 2012-04-03T20:53:04.580 に答える