-3

I have such piece of code:

template <class T>
struct Rgb
{
    T *r, *g, *b;

    Rgb(int nr, int ng, int nb)
    {
        r = new T(nr);
        g = new T(ng);
        b = new T(nb);
    }

    Rgb(int n)
    {
        Rgb(n, n, n);
    }

    ~Rgb()
    {
        delete r;
        delete g;
        delete b;
    }
};

I have done it in such way, because I want to be able to create objects like:

    Rgb<std::vector<int>> a(10); // so it creates 3 vectors inside,
        // each with 10 elements or

    Rgb<std::deque<double>> a(2, 5, 4); // so it creates 3 deques inside
        // with different sizes

But the implementation I have given above does not work. Help me please... thanks...

deathmood
  • 113
  • 6

1 Answers1

1

If you compiler supports constructor delegation (which e.g. Clang 3.2 does) you can do the following:

    Rgb(int n) : Rgb(n, n, n)
    {
    }

What you're doing is constructing a temporary Rgb instance in the constructor, which will fail once the uninitialized r, g and b get deleted.

Otherwise I'd recommend either creating a common init function that does the initialization or simply duplicate the code. And as the comments are noting you shouldn't use new here (that's almost always a code smell in modern C++ code). Bringing this together:

template <class T>
struct Rgb
{
    T r, g, b;

    Rgb(int nr, int ng, int nb) : r(nr), g(ng), b(nb)
    { }

    Rgb(int n) : r(n), g(n), b(n)
    { }

    ~Rgb()
    { }
};
user786653
  • 29,780
  • 4
  • 43
  • 53
  • 2
    VC11 supports constructor delegation if you install the [Nov 2012 CTP](https://www.microsoft.com/en-us/download/details.aspx?id=35515) – Praetorian Feb 01 '13 at 17:17
  • Thanks)) That solved my problem)) I did not even knew about NOV CTP for VC11)) – deathmood Feb 01 '13 at 17:44