Sorry I ill formed the question earlier. The piece of code is something like:
class Bar
{
public:
// some stuff
private:
struct Foo
{
std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo;
// some other basic variables here
};
Foo foo;
};
I got the basic idea about subFoo
. But I am wondering that a single instance of Bar
will contain only a single instance of Foo
that is foo
member variable? So a single instance/object of Bar will not be able to map multiple Foo
inside the subFoo
?
It feels like I am missing something here, can anyone break it down for me?
CodePudding user response:
There are more misunderstandings about nested class definitions than there are actual benefits. In your code it really does not matter much and we can change it to:
struct Foo {
std::unordered_map<std::string, std::unique_ptr<Foo>> subFoo;
// some other basic variables here
};
class Bar
{
Foo foo;
};
Foo
is now defined in a different scope and it is no longer private
to Bar
. Otherwise it makes no difference for the present code.
I am wondering that a single instance of Bar will contain only a single instance of Foo that is foo member variable?
Yes.
So a single instance/object of Bar will not be able to map multiple Foo inside the subFoo?
subFoo
is a map holding unique pointers to Foo
s. Bar::foo
is not managed by a unique pointer, hence placing them in subFoo
is not possible without running into a double free error. std::unique_ptr
can be used with a custom deleter, but thats not the case here. Hence you cannot store a unique pointer to Bar::foo
in any Foo::subFoo
. You can however, store unique pointers to other Foo
s in Foo::subFoo
.