0

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;
}
CY5
  • 1,551
  • 17
  • 23
  • 1
    "Correctly printing" is one possible outcome. Your program has undefined behavior. Add the compiler options `-g -fsanitize=address,undefined` – Ted Lyngmo Aug 07 '21 at 10:10
  • as you can see i've added godbolt compiler link https://godbolt.org/z/zT61KoGqK even there its not complaining about any error or warning i think they already have this flag enabled right? – CY5 Aug 07 '21 at 10:11
  • No, those options are not enabled by default. Just add them and you'll see. – Ted Lyngmo Aug 07 '21 at 10:14
  • yes it giving error now thnks (voted +1) but still don't understand why its correctly printing. – CY5 Aug 07 '21 at 10:17
  • 1
    A program that has [_undefined behavior_](https://en.cppreference.com/w/cpp/language/ub) (like this program has) can do pretty much _anything_. – Ted Lyngmo Aug 07 '21 at 10:18
  • You are confusing "valid" with "works for me". – n. m. could be an AI Aug 07 '21 at 10:32
  • @n.1.8e9-where's-my-sharem. valid code for me means "production ready code". – CY5 Aug 07 '21 at 10:34
  • 1
    Undefined behavior is undefined. "Seems to work" is one possible manifestation of undefined behavior. "Works in tests but crashes during a demonstration in front of an important customer" is another. – Igor Tandetnik Aug 07 '21 at 18:00
  • @CY5 Anytime _undefined behavior_ is identified in your code by you, or anyone else, do not ship it - even if it seems to work. I think that's the general message we're trying to send. It will cause problems - sometimes **big** problems. Don't do it. – Ted Lyngmo Aug 07 '21 at 21:48

0 Answers0