Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does using conditional operator ? : causes returning local temporary object?

I run into a problem where using the conditional operator returns garbage string_view in MSVC, because the string_view was backed by a temp object?.

#include <string>
#include <iostream>

std::string hello("Hello");
char world[6] = { "World" };

std::string_view ChooseString( bool first )
{
    // warning: returning address of local temporary object
    return first ? hello : world; // returned string_view is garbage
    
    // all other ways of returning string_view works fine
    /*if ( first )
        return hello;
    else
        return world;*/
    //return first ? std::string_view( hello ) : std::string_view( world );
    //return hello;
    //return world;
}

int main()
{
    std::cout << ChooseString(true) << std::endl;
    std::cout << ChooseString(false) << std::endl;
}

Then I tried clang and gcc on goldbot, they had the same behavior, where clang gave warning: returning address of local temporary object. Also just returning hello or world were fine too. Can someone explain why the first way returns temporary object?

Is it because a string object is constructed after conditional operator is evaluated?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, the return type of condition operator is the common type of the operands. Given first ? hello : world;, i.e. the types of operands are std::string and const char[], the common type will be std::string. A temporary std::string needs to be constructed for world then the temporary is used to construct the std::string_view which is returned later.

On the other hand for first ? std::string_view( hello ) : std::string_view( world ) the return type is std::string_view, and all std::string_views are constructed from hello and world directly, then no trouble as above.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading