Sample is passed by the value of SomeFunc , which means that a copy is made. The copy has the same ptr , so when this copy is destroyed, when SomeFunc returns, ptr is deleted for both objects. Then, when you call PrintVal() in the main, you PrintVal() this invalid pointer. This behavior is undefined. Even if it works, when s1 destroyed, ptr is deleted again, which is also UB.
In addition, if the compiler does not delete the copy in Sample s1= 10; , then s1 will not even be valid for starters, because with temporary destruction, the pointer will be deleted. However, most compilers avoid this copy.
You need to either copy correctly or deny copying. Copy-ctor is incorrect by default for this type. I would recommend either making this type a value type (which contains its members directly, not by pointer), so copy-ctor works by default or uses a smart pointer to store the link so that it can manage the resources for the link for you and copy- ctor will work by default.
One of the things that I really like in C ++ is that it is really friendly with the use of value types around the world, and if you need a reference type, you can simply wrap any value type in a smart pointer. I think this is much better than other languages ββthat have primitive types with semantics, but then user-defined types have reference semantics by default.
source share