unique_ptr problem

Why can't I do something like this ?

1
2
3
4
5
6
7
8
9
class Thing
{
   ......
};

Thing thing;
Thing *pthing = &thing;

std::unique_ptr<*pthing> pthing2(new *pthing)


It says unique_ptr needs a type specifier.
std::uniqe_ptr<Thing> pthing2(new Thing);
Yeah, I know I can do that, but say I want to do something like this:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Base
{
    .......
}

class Derived1 : public Base
{
    .........
}

class Derived2 : public Base
{
    ..........
}

Derived1 derived1;
Derived2 derived2;

std::vector<Base*> vec;

vec.push_back(derived1*);
vec.push_back(derived2*);


So now, you don't know exactly what class you want for the earlier example I mentioned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <random>
#include <memory>
#include <vector>
#include <iostream>

struct A
{
    virtual void display(std::ostream& os) { os << "A\n"; }

    virtual ~A() =0 {}
};

struct B : public A
{
    void display(std::ostream& os) { os << "B\n"; }
};

struct C : public A
{
    void display(std::ostream& os) { os << "C\n"; }
};

int main()
{
    std::mt19937 engine((std::random_device()()));
    std::uniform_int_distribution<unsigned> dist(0, 1);

    std::vector<std::unique_ptr<A>> container;

    for (unsigned i = 0; i < 20; ++i)
        if (dist(engine))
            container.emplace_back(new B);
        else
            container.emplace_back(new C);

    for (auto& element : container)
        element->display(std::cout);
}
Topic archived. No new replies allowed.