微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

std::make_pair 的一些奇怪行为,并扣除了 string_view

如何解决std::make_pair 的一些奇怪行为,并扣除了 string_view

{
   "StartAt":"Dummy Step 1 Output","States":{
      "Dummy Step 1 Output":{
         "Type":"Pass","Result":[
            "iter 1","iter2"
         ],"ResultPath":"$.inputForMap","Next":"does map has atleast one record?"
      },"does map has atleast one record?":{
         "Type":"Choice","Choices":[
            {
               "Variable":"$.inputForMap[0]","IsPresent":true,"Next":"loop on map"
            }
         ],"Default":"End of Step Function"
      },"End of Step Function":{
         "Type":"Pass","End":true
      },"Step three":{
         "Type":"Pass","Next":"End of Step Function"
      },"loop on map":{
         "Type":"Map","Next":"Step three","Iterator":{
            "StartAt":"Step 2 - Looping on map","States":{
               "Step 2 - Looping on map":{
                  "Type":"Pass","End":true
               }
            }
         },"ItemsPath":"$.inputForMap","MaxConcurrency":1
      }
   }
}

用c++17编译这将输出

std::string api_key_ = "123456789-5c51509f-8c5c5dc2-b6557";
std::pair<std::string_view,std::string_view> yy = std::make_pair("AccessKeyId",api_key_);
std::cout << "yy.second:" << yy.second << std::endl;

虽然这很好,没有扣除

yy.second:9-5c51509f-8c5c5dc2-b6557

输出

std::string api_key_ = "123456789-5c51509f-8c5c5dc2-b6557";
std::string_view sv = api_key_;
std::cout << "sv:" << sv << std::endl;

std::pair<std::string_view,std::string_view> xx = std::make_pair<std::string_view,std::string_view>("AccessKeyId",api_key_);
std::cout << "xx.second:" << xx.second << std::endl;

谁能解释一下?谢谢。 完整代码如下:

sv:123456789-5c51509f-8c5c5dc2-b6557
xx.second:123456789-5c51509f-8c5c5dc2-b6557

编译输出

#include <unordered_map>
#include <iostream>
#include <variant>
#include <deque>
#include <vector>

int main() {
    std::string api_key_ = "123456789-5c51509f-8c5c5dc2-b6557";
    std::string_view sv = api_key_;
    std::cout << "sv:" << sv << std::endl;

    std::pair<std::string_view,api_key_);
    std::cout << "xx.second:" << xx.second << std::endl;

    std::pair<std::string_view,api_key_);
    std::cout << "yy.second:" << yy.second << std::endl;
}

解决方法

std::make_pair("AccessKeyId",api_key_); 返回一个临时数组 std::pair,其第二个元素是 std::string。然后从临时对象初始化 yy,它的第二个元素 std::string_view 是从临时对象 std::stringstd::pair 构造的(但不是 api_key_)。完整表达式后,临时 std::pair 被销毁,左 yy 的第二个元素持有一个悬空指针。

std::make_pair<std::string_view,std::string_view>("AccessKeyId",api_key_) 也返回一个临时的 std::pair,但它的第二个元素是一个由 std::string_view 构造的 api_key_。然后 xx 的第二个元素从临时 std::string_viewstd::pair 初始化并引用 api_key_,这就是它有效的原因。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。