Is it safe to use emplace_back with a container of unique_ptrs?

前端 未结 1 1385
自闭症患者
自闭症患者 2020-12-15 18:39

Consider the following:

std::vector> ptrsToInts;
ptrsToInts.emplace_back(new int);

If reallocation occurs

相关标签:
1条回答
  • 2020-12-15 18:46

    If reallocation is required and it fails, then yes, your object never went into the container and will thus be lost.

    However, it should be noted that this is pure user error. emplace_back should not be "banned" for containers of unique_ptr, because there are perfectly safe ways of doing this (such as reserveing the space beforehand, so you know it will always be there). Also, you can pass in whole unique_ptrs, since it's perfectly capable of using a move constructor.

    So really, it's your fault for not properly wrapping your non-RAII object (the int*) in a RAII object before the point where you could throw exceptions.

    0 讨论(0)
提交回复
热议问题