Pedro David
Pedro David

Reputation: 377

Alternative to Initializer List of References

I really needed and Initializer List of References but it seems that is not possible. The problem of being a copy is that I wanted to disable copy construction and because these copies call the destrutor afterwards what releases the resources(and should not happend).

My current (bad) alternative is using a bool to track if it was copy constructed so the resources are not released.

Another alternative is an Initializer List of Pointers but that makes it more verbose and would accept nullptr as well as being conceptually incorrect in my opinion.

I would really like an alternative using references or something along those lines (maybe move? I can't seem to make that work)

Upvotes: 1

Views: 424

Answers (1)

Guilherme Ferreira
Guilherme Ferreira

Reputation: 459

I assume you want an initializer list of references of references to put in a container. So, you are looking for a reference type, right? If it's so, check the Reference Wrappers. It allows references to be the type of containers:

#include <iostream>
#include <functional>

struct A {
    A() { std::cout << "A()" << std::endl; }
    A(const A&) = delete;
    ~A() { std::cout << "~A()" << std::endl; }
};

int main(int argc, char const *argv[])
{
    A a1;
    A a2;
    A a3;

    {
        // OK: don't call copy constructor during creation
        std::initializer_list<std::reference_wrapper<A>> ilist{ a1, a2, a3 };
        // OK: don't call destructor when "ilist" leaves the scope
    }

    {
        // ERROR: can't create the list because copy constructor is deleted
        std::initializer_list<A> va{ a1, a2, a3 };
    }


    // Destructors called here

    return 0;
}

Upvotes: 2

Related Questions