c++ - How to: copying an instance of a class without a proper default constructor; that has members without a default constructor? -
// b doesn't have default constructor. class { public: a(important resource) : b(resource) {} b b; };
reading rule of three figure out issue copying instances of class vector.
so issue we're generating instances inside loop:
std::vector<a> some_vector(0); (int = 0; < 7; i++) some_vector.push_back(a(resources[i]));
from see valgrind, smells copy constructor mucking things up. when change code to:
std::vector<a*> some_vector(0); (int = 0; < 7; i++) some_vector.push_back(new a(resources[i]));
the issue alleviated. don't doing though when not needed. i'm thinking, how copy constructor know when attempting copy class without proper default constructor right?
for elements of type t pushed std::vector in c++,
t must meet requirements of copyassignable , copyconstructible.
this means must have working move or copy-constructor used when creating new objects. not need default constructor in general, operations may require it, e.g. resize
.
being resource in example, should non-copyable, maybe movable. if b not have correct copy-constructor, end copy of resource, , destructor release resource more once (e.g. deallocate memory or close file).
for resources, common pattern use raii, e.g. std::unique_pointer memory.
ps: since c++11, there new type of constructor/assignment operator. rule of 3 becomes rule of five, best not write copy- or assignment constructors @ when not dealing resource-handling classes. these need implement operations, , other classes can use it. rule of zero, , recommend stick to. again, std::unique_pointer
example. instead of writing move/copy-constructors, classes can use unique_ptr
or shared_ptr
, , memory management taken care of.
Comments
Post a Comment