Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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;
compile with c++17 this will output:
yy.second:9-5c51509f-8c5c5dc2-b6557
while this is good without deduction
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;
output:
sv:123456789-5c51509f-8c5c5dc2-b6557
xx.second:123456789-5c51509f-8c5c5dc2-b6557
Can anybody explain? Thanks.
the complete code is as below:
#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, std::string_view> xx = std::make_pair<std::string_view, std::string_view>("AccessKeyId", api_key_);
std::cout << "xx.second:" << xx.second << std::endl;
std::pair<std::string_view, std::string_view> yy = std::make_pair("AccessKeyId", api_key_);
std::cout << "yy.second:" << yy.second << std::endl;
compile and output:
$ g++ ./try2.cpp -std=c++17
$./a.out
sv:123456789-5c51509f-8c5c5dc2-b6557
xx.second:123456789-5c51509f-8c5c5dc2-b6557
yy.second:9-5c51509f-8c5c5dc2-b6557
std::make_pair("AccessKeyId", api_key_);
returns a temproray std::pair
whose 2nd element is an std::string
. Then yy
is initialized from the temporary and its 2nd element std::string_view
is constructed from the std::string
of the temporary std::pair
(but not api_key_
). After the full expression the temporary std::pair
gets destroyed, left yy
's 2nd element holding a dangling pointer.
std::make_pair<std::string_view, std::string_view>("AccessKeyId", api_key_)
returns a temporary std::pair
too, but its 2nd element is an std::string_view
constructed from api_key_
. Then xx
's 2nd element is initialized from the std::string_view
of the temporary std::pair
and referring to api_key_
too, that's why it's valid.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.