samedi 7 août 2021

why const ref of string in the program is still valid?

in below program a string cstis created inside the block scope and store its const reference in unique_ptr<Def> d(unique_ptr<Def> d is outside block scope). as per my understanding when the block scope ends string cst is destroyed, so unique_ptr<Def> d storing reference of string cst should be dangling after end of block scope but its not and it correctly printing "Hello" string. i've check the address of d->s and cst are same so there is no copy happening so wanted to know why d->s retains the string value even aftercst doesn't exist? o/p : https://godbolt.org/z/zT61KoGqK

#include <iostream>
#include <string>
#include <memory>

using namespace std;

struct Def
{
    const string& s;
    Def(const string& v):s(v)
    {
    }
};
int main()
{
    unique_ptr<Def> d = nullptr;
    {
        string cst = "Hello";
        d.reset(new Def(cst));
        std::cout <<&d->s <<"="<< &cst<<"\n";
    }
    std::cout << "strVal : " << d->s<<  "\n";

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire