在制作std :: string副本时的分配

Dan*_* K. 0 c++ string stl

您认为哪种实施更好?

std::string ToUpper( const std::string& source )
{
    std::string result;
    result.resize( source.length() );
    std::transform( source.begin(), source.end(), result.begin(), 
        std::ptr_fun<int, int>( std::toupper ) );
    return result;
}
Run Code Online (Sandbox Code Playgroud)

和...

std::string ToUpper( const std::string& source )
{
    std::string result( source.length(), '\0' );
    std::transform( source.begin(), source.end(), result.begin(), 
        std::ptr_fun<int, int>( std::toupper ) );
    return result;
}
Run Code Online (Sandbox Code Playgroud)

区别在于第一个使用reserve默认构造函数之后的方法,但第二个使用接受字符数的构造函数.

编辑 1.我不能使用boost lib.我只是想在构造函数之间的分配和构造函数之后分配之间进行比较.

Nik*_*kko 5

怎么样简单:

std::string result;
result.reserve( source.length() );

std::transform( source.begin(), source.end(), 
                std::back_inserter( result ),
                ::toupper );
Run Code Online (Sandbox Code Playgroud)

然后我亲自使用boost.