Because you create two Person
objects in your code.
Take a look at this explanation at your code:
class Person // declare a class Person
{
public:
string s;
~Person(){ cout << "Destructor" << endl; }
};
// function that takes a class Person as argument
void _Person(Person a) {
cout << a.s << endl;
}
auto main() ->int
{
unique_ptr<Person> p{new Person()}; // creation of one instance
_Person(*p); // creation of second instance,
// because p is passed by value, which means that the default copy constructor of the
// class Person is activated, thus another object is created!!
// when the function you called terminates, the copy goes out of scope,
//thus ~Person() is called
cout << "New Line" << endl;
return 0;
}
// the object you created by new, now goes out of scope and gets deleted,
//thus ~Person() is called
But unique_ptr
allows us to create another object?
Of course. Check out the ref.
These pointers are unique for deleting the object.
[EDIT]
Take this into account:
A singleton ensures only one instance of a type.
A unique_ptr
ensures only one smart pointer to any instance.
Source
[EDIT.2]
Nice link from chris, which talks about the rules for using an underscore.
To be laconic, I would suggest to change this:
_Person()
to this
Person()
It's not a compilation mistake, it's just not common.
[EDIT.3]
Generally in C++, you can pass class objects as references, in order to avoid copying. Copying can take some time when the objects are instances of big classes.
So, I suggest that you change your function:
void Person(Person a) {
cout << a.s << endl;
}
to this
void Person(Person& a) {
cout << a.s << endl;
}
and run again your code. Can you guess what the output should be now? We pass the instance by reference, thus no copy constructor of Person
is called.