0

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 all 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;
}
sunshilong369
  • 646
  • 1
  • 5
  • 17
  • 2
    In your question you said `new Sample[]`, but in your code it seems to be `new Sample()`, which one is correct? – songyuanyao May 27 '20 at 05:41
  • @songyuanyao The latter one is right.Sorry to disturbing you.I have modified it. – sunshilong369 May 27 '20 at 05:45
  • Does this answer your question? [Why is list initialization (using curly braces) better than the alternatives?](https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives) – Daniel H May 27 '20 at 05:47
  • I would see it right now.Thank you. – sunshilong369 May 27 '20 at 05:51

2 Answers2

2

They have the same efffect here.

new Sample() performs value initalization, the object is initialized by the default constructor of Sample.

new Sample{} performs list initialization (since C++11), as the effect the object is also value-initialized by the default constructor of Sample.

BTW: new Sample has the same effect too, it performs default initialization and the object is also initialized by the default constructor.

The effect of these initalization styles depend on contexts, especially on how the type behaves. For class Sample they all have the same effect.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

{} can be used to directly initialize member data in the absence of a constructor.

() can be used only without any parameters in the absence of a constructor that takes parameters.

In your case, they will perform the same because you have a defined constructor.

A quick example:

struct h
{
    int tmp=3;
    int k=3;
};


int main()
{
    h h1{6, 4};
    h h2;

    std::cout << h1.tmp << std::endl;
    std::cout << h2.tmp << std::endl;

    return 0;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
bhristov
  • 3,137
  • 2
  • 10
  • 26