Yurii Komarnytskyi
Yurii Komarnytskyi

Reputation: 173

Function parameter life time

I though that after function call all rvalue parameters send to function will be destroyed. I'm completely messed up with this example. Can someone help me with it? Maybe some links where it explained.

class Test
{
public:
    Test(const char* name)
        : ptr(nullptr)
    {
        ptr = name;
    }

    ~Test()
    {
        printf("%s\n", ptr);
        system("PAUSE");
    }

    const char* ptr;
};

int main()
{
    Test t("Hello");
}

Upvotes: 0

Views: 66

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145379

"Hello" is a string literal. The string is a basic value that has static lifetime. Same as 42: that number is never destroyed.


In other news:

  • Initializing ptr to null, and a nanosecond later assigning to it, is perplexing and can therefore waste some programmer's time. Just initialize it to the value it should have.

  • Pausing a program at the end serves no purpose and can be a practical problem, so just don't. To see the program's output when you run it from some IDE, use the appropriate way to run it. E.g. Ctrl+F5 in Visual Studio.

  • It's generally a good idea to adopt some special naming conventions for data members. E.g., ptr_, or my_ptr, or myPtr, or mPtr (I prefer the first). However, don't use _ptr, as some beginners do, because that conflicts with a convention used to keep C and C++ implementation global names separate.

Upvotes: 5

Related Questions