c++11 & 14: unique_ptr shared_ptr std::make_unique(c++14)
2015-07-02 11:21
585 查看
参考网站:
http://www.cplusplus.com/reference/utility/pair/
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type
can refer to a resource.
When using
there can be at most one
at any one resource. When that
destroyed, the resource is automatically reclaimed. Because there can only be one
any resource, any attempt to make a copy of a
cause a compile-time error. For example, this code is illegal:
However,
be moved using the new move semantics:
Similarly, you can do something like this:
This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of
a safer, better replacement for
on the other hand, allows for multiple pointers to point at a given resource. When the very last
a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
Internally,
counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
In short:
Use
you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
Use
you want multiple pointers to the same resource.
Hope this helps!
C++
Utilities library
Dynamic memory management
std::unique_ptr
Constructs an object of type
1) Constructs a non-array type
The arguments
The function does not participate in the overload resolution if
2) Constructs an array of unknown bound
The function does not participate in the overload resolution unless
equivalent to:
3) Construction of arrays of known bound is disallowed.
std::unique_ptr of
an instance of type
May throw std::bad_alloc or any exception thrown by the constructor of
If an exception is thrown, this function has no effect.
Run this code
Output:
http://www.cplusplus.com/reference/utility/pair/
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type
can refer to a resource.
When using
unique_ptr,
there can be at most one
unique_ptrpointing
at any one resource. When that
unique_ptris
destroyed, the resource is automatically reclaimed. Because there can only be one
unique_ptrto
any resource, any attempt to make a copy of a
unique_ptrwill
cause a compile-time error. For example, this code is illegal:
unique_ptr<T> myPtr(new T); // Okay unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr
However,
unique_ptrcan
be moved using the new move semantics:
unique_ptr<T> myPtr(new T); // Okay unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr
Similarly, you can do something like this:
unique_ptr<T> MyFunction() { unique_ptr<T> myPtr(/* ... */); /* ... */ return myPtr; }
This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of
unique_ptras
a safer, better replacement for
auto_ptr.
shared_ptr,
on the other hand, allows for multiple pointers to point at a given resource. When the very last
shared_ptrto
a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:
shared_ptr<T> myPtr(new T); // Okay shared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.
Internally,
shared_ptruses reference
counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.
In short:
Use
unique_ptrwhen
you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
Use
shared_ptrwhen
you want multiple pointers to the same resource.
Hope this helps!
std::make_unique
C++Utilities library
Dynamic memory management
std::unique_ptr
Defined in header <memory> | ||
template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args ); | (1) | (since C++14) (only for non-array types) |
template< class T > unique_ptr<T> make_unique( std::size_t size ); | (2) | (since C++14) (only for array types with unknown bound) |
template< class T, class... Args > /* unspecified */ make_unique( Args&&... args ) = delete; | (3) | (since C++14) (only for array types with known bound) |
Tand wraps it in a std::unique_ptr.
1) Constructs a non-array type
T.
The arguments
argsare passed to the constructor of
T.
The function does not participate in the overload resolution if
Tis an array type. The function is equivalent to:
unique_ptr<T>(new T(std::forward<Args>(args)...))
2) Constructs an array of unknown bound
T.
The function does not participate in the overload resolution unless
Tis an array of unknown bound. The function is
equivalent to:
unique_ptr<T>(new typename std::remove_extent<T>::type[size]())
3) Construction of arrays of known bound is disallowed.
Parameters
args | - | list of arguments with which an instance of Twill be constructed. |
size | - | the size of the array to construct |
Return value
std::unique_ptr ofan instance of type
T.
Exceptions
May throw std::bad_alloc or any exception thrown by the constructor of T.
If an exception is thrown, this function has no effect.
Example
Run this code#include <iostream> #include <memory> struct Vec3 { int x, y, z; Vec3() : x(0), y(0), z(0) { } Vec3(int x, int y, int z) :x(x), y(y), z(z) { } friend std::ostream& operator<<(std::ostream& os, Vec3& v) { return os << '{' << "x:" << v.x << " y:" << v.y << " z:" << v.z << '}'; } }; int main() { // Use the default constructor. std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>(); // Use the constructor that matches these arguments std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2); // Create a unique_ptr to an array of 5 elements std::unique_ptr<Vec3[]> v3 = std::make_unique<Vec3[]>(5); std::cout << "make_unique<Vec3>(): " << *v1 << '\n' << "make_unique<Vec3>(0,1,2): " << *v2 << '\n' << "make_unique<Vec3[]>(5): " << '\n'; for (int i = 0; i < 5; i++) { std::cout << " " << v3[i] << '\n'; } }
Output:
make_unique<Vec3>(): {x:0 y:0 z:0} make_unique<Vec3>(0,1,2): {x:0 y:1 z:2} make_unique<Vec3[]>(5): {x:0 y:0 z:0} {x:0 y:0 z:0} {x:0 y:0 z:0} {x:0 y:0 z:0} {x:0 y:0 z:0}
See also
(constructor) | constructs a new unique_ptr (public member function) |
相关文章推荐
- C++ Primer 学习笔记(1)——巧妙利用cin返回值为其左操作数的特点
- MFC,VC++中,CView类意外消失
- C++ Sort类成员的传递
- JNI初次使用---在C++中得到一系列圆并返回ArrayList
- C/C++中函数参数传递详解
- 数独检测器:帝国理工C++作业
- 2048控制台程序:一份帝国理工C++作业
- 在C++ 中 如何调用 C# 写的DLL
- c语言结构体中保存函数指针的用法
- C++ STL中常见容器的时间复杂度
- 黑马程序员---C语言基础---语句概述
- C/C++中善用大括号
- C语言关键字auto与register的深入理解
- C++中的四种强制类型转换的区别
- 【c语言】模拟实现strchr函数,功能:在一个字符串中查找一个字符第一次出现的位置,如果没有出现返回NULL
- C++ 类继承与对象赋值 情况下 成员变量的覆盖 浅析
- 【c语言】编写程序,使字符串逆序,空间复杂度O(1)
- 【c语言】 模拟实现库函数strcat函数
- C语言中关于错误输出的函数
- 【c语言】模拟实现库函数strcpy函数