小编Ton*_*y J的帖子

为什么使用条件运算符?:导致返回本地临时对象?

我遇到一个问题,即使用条件运算符在 MSVC 中返回垃圾 string_view,因为 string_view 由临时对象支持?。

#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 …
Run Code Online (Sandbox Code Playgroud)

c++ compiler-warnings

5
推荐指数
1
解决办法
128
查看次数

标签 统计

c++ ×1

compiler-warnings ×1