简体   繁体   中英

C++11 object composition with abstract classes

Let's say I have a class Foo that has a const member of an abstract class Bar, what is the correct way to pass Bar in the constructor to initialize the const member?

class Foo
{
public:
    Foo(?Bar? bar): bar(?bar?) {};
private:
    const ?Bar? bar;
}

In C++11 I was thinking of using std::unique_ptr like so:

class Foo
{
public:
    Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
private:
    const std::unique_ptr<Bar> bar;
}

Is this the best way to do it? What are the other ways and when should I use them?

In...

struct Foo
{
public:
    Foo(std::unique_ptr<Bar> &bar): bar(std::move(bar)) {};
    const std::unique_ptr<Bar> bar;
};

... bar (the pointer) is not modifiable, but the value to which is points is.

Is this what you want?

I would rather think:

class Foo
{
public:
    Foo(std::unique_ptr<const Bar>& bar): bar(std::move(bar)) {}

private
    std::unique_ptr<const Bar> bar;
};

would be more appropriate, as not the value is truly constant. I suspect that this won't compile because the unique_ptr cannot call the destructor (specification of custom deleter springs to mind), but the value to which bar points is const, which is what you really want (I suspect).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM