Yurii Komarnytskyi Yurii Komarnytskyi - 1 year ago 75
C++ Question

Function argument 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
Test(const char* name)
: ptr(nullptr)
ptr = name;

printf("%s\n", ptr);

const char* ptr;

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

Answer Source

"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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download