mardi 26 mai 2020

Differences among `unique_ptr

What are the differences among unique_ptr<Sample> sp1(new Sample); unique_ptr<Sample> sp1(new Sample()); and , unique_ptr<Sample> sp2(new Sample{});? I found that they are both legal indeed.You could check it on http://cpp.sh/3icui.

I am a novice in C++.I thought over and over but still could get the idea.I would be thankful for any hint on this question.

#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>

using namespace std;

class Sample {
public:
    Sample() { cout << "Sample Constuctor" << endl; }
    ~Sample() { cout << "Sample Destructor" << endl; }
    void publicFn() { cout << "This is public function of class" << endl; }
};
int main() {
    unique_ptr<Sample> sp1(new Sample{});
    unique_ptr<Sample> sp2(new Sample());
    unique_ptr<Sample> sp3(new Sample);
    sp1->publicFn();
    sp2->publicFn();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire