I have a class, for which every instance is to be accounted for, creation and destruction regulated tightly. No random moves, copies, temporaries allowed - once created through a dedicated function, the instance can be "passed around" only through references and pointers.
To achieve that, I've deleted this class' copy constructor and assignment operator.
The instances were meant to be kept in std::list, created by emplace_back(), removed on demand and never intended to move. But I'm getting errors about the deleted copy constructor.
In constructor 'std::_List_node<_Tp>::_List_node(_Args&& ...)
error: deleted function 'Reader::Reader(const Reader&)
stl_list.h:103: error: used here
Is there a way to make this work? Some alternative to std::list that I won't need to carve by hand?
The answer to the question in the title is "It depends".
If your class does have a move constructor, you will be able to use the move constructor. If your class does not have a move constructor, then the copy constructor will be used.
The object in the list has to be constructed somehow. emplace_back
makes it as efficient as possible but it still needs to construct an object. From http://en.cppreference.com/w/cpp/container/list/emplace_back: uses placement-new to construct the element in-place at the location provided by the container.
When the argument to emplace_back
is another object, the placement new will end up calling either the copy constructor or the move constructor.
If the argument(s) to emplace_back
is just the data needed to construct an object, then you don't need a copy constructor or a move constructor.
Is there a way to make this work?
If your, or your team's, policy regarding copy constructor and move constructor is not open for discussion, you will have to use a work around.
Store pointers to the objects in the list. This is the simplest work around as long as you can ensure that objects are not deleted behind the list's back and leave the list holding on to dangling pointers.
Store a non-pointer handle to the objects in the list. This will require some book keeping code on your part. If you can add the ability to:
you can easily manage by using a list of handles.
The above can be easily accomplished by keeping couple of maps that are updated with construction and deletion of objects. Every time you create an object, you add entries to the maps. Every time you delete an object, you remove entries from the maps.