c++ - How to construct any object from variadic constructor parameters? -


i experimenting making own containers, , writing emplace method vector class.

first, here forward functions:

template<typename t> t&& forward(typename remove_reference<t>::type& arg) {     return static_cast<t&&>(arg); }  template<typename t> t&& forward(typename remove_reference<t>::type&& arg) {     static_assert(!internal::is_lvalue_reference<t>::result);      return static_cast<t&&>(arg); } 

they identical std ones.

now here emplace method:

template<typename t> template<class... args> void myvector<t>::emplace(args&&... args) {     add(forward<args>(args)...); } 

this gives me error "function not take 2 arguments", because add isn't designed work variadic arguments. instead in place:

template<typename t> template<class... args> void myvector<t>::emplace(args&&... args) {     if(size >= capacity)     {         adaptcapacity();     }      data[size++] = value; } 

what supposed put @ _data[_size++] = value;? how can construct 't' variadic arguments? if pass call of forward constructor of t, give me same error passing add, because of '...' syntax. else can do?

i tried looking inside std::vector , found function _alty_traits::construct doesn't seem have definition(a compiler intrinsic?)

does mean it's impossible me write custom emplace method?

normally, if date vector<t> or such, do:

date[size++] = t(std::forward<args>(args)...); 

however, if writing own vector, data holds raw memory. need construct object directly raw memory. that, need placement new:

new (date + size++) t(std::forward<args>(args)...); 

note placement new issue orthogonal using variadics , such; need placement new when writing push_back well.

edit: because did not tells type or content of date, , based on comments here, i'm assuming did this:

data = new t[capacity]; 

if did, must use first form gave; using second form undefined because constructing object on object (and can never call destructor).

however, not correct way write vector (or other generic container). when vector grabs more memory, should only grab more memory , not construct (new t[capacity] default constructs entries in dynamic array), in case must use second form.


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -