On 24.08.2016 21:28, bitrex wrote:
> Having a bit of trouble with code like this (still getting acquainted
> with 21st century C++):
>
> #include <vector>
> #include <memory>
>
> template <typename T>
> class Foo {
> public:
> Foo() = default;
> ~Foo() = default;
>
> private:
> std::unique_ptr<std::vector<T>> baz =
> std::unique_ptr<std::vector<T>>(new std::vector<T>());
> };
Oh my. Much of the point of `std::vector` is that it automates the
memory management. Adding memory management on top of that is, well, not
needed.
> template <typename T>
> class Bar {
> public:
> Bar(size_t foonum)
> {
> for (size_t n = 0; n < foonum; ++n) {
> bip->push_back(Foo<T>());
> }
> }
>
> ~Bar() = default;
>
> private:
> std::unique_ptr<std::vector<Foo<T>>> bip =
> std::unique_ptr<std::vector<Foo<T>>>(new std::vector<Foo<T>>());
>
> };
Ditto, that's just asking for problems.
> int main()
> {
> Bar<uint32_t> bar(10);
> return 0;
`return 0;` is the default for `main`.
> }
>
> Seems like it's complaining about the new Foo<T> object not being able
> to be pushed back into "bip" because it can't use the default
> copy-constructor for that class (as unique_ptrs aren't copyable.) What's
> the correct way to do this?
Just use `std::vector` directly.
[code]
#include <vector>
#include <stddef.h>
template< class Type >
class Foo
{
private:
std::vector<Type> baz;
public:
Foo() = default;
~Foo() = default;
};
template < class Type >
class Bar
{
private:
std::vector<Foo<Type>> bip;
public:
Bar( int const foonum )
: bip( foonum, Foo<Type>() )
{}
~Bar() = default;
};
auto main()
-> int
{
Bar<int> bar{ 10 };
(void) bar;
}
[/code]
Cheers & hth.,
- Alf