c++ - std::vector pointer with data swap -
in section of code below, resultant memory structure after swap? there leak because have swapped memory addresses underneath? fine because did deep copy? if code stuck inside of class , swapping working buffer piece of dynamic memory?
#include <iostream> #include <vector> int main() { std::vector<std::string> * ptr_str_vec = new std::vector<std::string>(); ptr_str_vec->push_back("hello"); std::vector<std::string> str_vec; str_vec.push_back("world"); ptr_str_vec->swap(str_vec); delete ptr_str_vec; //what resulting structures? return 0; }
edit: posted faulty code. fixed errors.
when vector created, underlying continuous data block used vector default created heap. in case, since didn't supply allocator, default 1 used.
int main() { std::vector<std::string> * ptr_str_vec = new std::vector<std::string>(); // #^&! *ptr_str_vec allocated heap. vector's data block allocated heap. ptr_str_vec->push_back("hello"); // #^&! "hello" copied onto heap block #1 std::vector<std::string> str_vec; // #^&! str_vec allocated stack. vector's data block allocated heap. str_vec.push_back("world"); // #^&! "world" copied onto heap block #2 ptr_str_vec->swap(str_vec); // #^&! swap fast o(1), done swapping block #1 , #2's address. no data copy done during swap. delete ptr_str_vec; // #^&! delete ptr_str_vec heap block #2. //what resulting structures? / return 0; // #^&! delete str_vec heap block #1 }
Comments
Post a Comment