c++ : new 在特定指针处构造初始化
2016-07-15 15:36
483 查看
C++ operator new 在特定指针处构造初始化
我认为, 从安全和简化代码的角度考虑, 在编写C++代码时,使用STL或其他模板库自动管理内存,
比通过new关键字或malloc动态声明空间,
更规范更安全, 带来的额外性能开销相比于开发效率的提升, 也可接受.
但在一些应用场景固定的模块中, 手动申请内存会带来更高的执行效率.
使用new可以向系统申请内存, 这也是最常见的做法.
也可以使用new在原指针处构造初始化, 而不申请内存.
new 语法
例如, 定义以下的类, 简单地表示一个点:class PointD { public: PointD(double x, double y) : x(x), y(y) { } void show() const { cout << x << " " << y << endl; } private: double x; double y; };
向系统申请内存, 并进行初始化的语句为:
PointD* point = new PointD(0, 0);
不申请内存, 在原指针处进行初始化的语句为:
PointD* point2 = new (point) PointD(2, 2);
执行这两句后, point和point2实际指向同一块内存, 只需要delete一次.
new 用法
vector使用的空间是连续的.通过索引, 我们能访问到vector中存储的数据, 能对数据进行修改.
通过new在原指针处构造初始化, 可以直接对vector中存储的数据重新构造初始化.
vector中的数据, 会随vector的析构而析构释放.
使用的情形:
将原始数据存放在固定的
vector<PointD>中, 函数传参使用
vector<PointD*>,
减少修改函数及调用函数的开销.
链接
我在这段代码中第一次发现这段代码:https://github.com/idiap/mser
该网页上, 有准确的解释:
http://www.cplusplus.com/reference/new/operator%20new
我的测试代码 (Visual Studio 2013):
vector<PointD*> pointers; { vector<PointD> values; values.push_back(PointD(1, 2)); values.push_back(PointD(3, 4)); cout << "[value] origin: " << endl; for (vector<PointD>::iterator vStart = values.begin(), vEnd = values.end(); vStart != vEnd; ++vStart) { vStart->show(); } pointers.push_back(new (&values[0]) PointD(4, 5)); pointers.push_back(new (&values[1]) PointD(6, 7)); cout << "[value] after 'new': " << endl; for (vector<PointD>::iterator vStart = values.begin(), vEnd = values.end(); vStart != vEnd; ++vStart) { vStart->show(); } } cout << "[pointer] after original value been destructed." << endl; for (vector<PointD*>::iterator pStart = pointers.begin(), pEnd = pointers.end(); pStart != pEnd; ++pStart) { cout << *pStart << endl; (*pStart)->show(); }
相关文章推荐
- C++ 之旅:前言
- 分辩零钱-20151108
- c++: stringstream的使用
- c++: Learning Resources
- c++: new, delete, malloc, free的匹配使用
- 计算程序执行时间c_c++
- c++/qt 23种设计模式
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 107. Binary Tree Level Order Traversal II
- Leetcode 108. Convert Sorted Array to Binary Search Tree
- Leetcode 109. Convert Sorted List to Binary Search Tree
- Leetcode 110. Balanced Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- Leetcode 112. Path Sum
- Leetcode 113. Path Sum II
- Leetcode 114. Flatten Binary Tree to Linked List
- Leetcode 115. Distinct Subsequences
- Leetcode 116. Populating Next Right Pointers in Each Node
- Leetcode 117. Populating Next Right Pointers in Each Node II