Destroy std::vector without releasing memory

前端 未结 2 1310
-上瘾入骨i
-上瘾入骨i 2021-02-20 11:16

Lets say I have a function to get data into an std vector:

void getData(std::vector &toBeFilled) {
  // Push data into \"toBeFilled\"
}

2条回答
  •  鱼传尺愫
    2021-02-20 11:49

    No.

    The API you're using has a contract that states it takes ownership of the data you provide it, and that this data is provided through a pointer. This basically rules out using standard vectors.

    Vector will always assuredly free the memory it allocated and safely destroy the elements it contains. That is part of its guaranteed contract and you cannot turn that off.

    You have to make a copy of the data if you wish to take ownership of them... or move each element out into your own container. Or start with your own new[] in the first place (ugh) though you can at least wrap all this in some class that mimics std::vector and becomes non-owning.

提交回复
热议问题