通过实际代码示例,展示了std::unique_ptr、std::make_unique和std::make_shared的创建机制,以及它们如何提高代码的安全性和健壮性 2.0 使用介绍std::make_unique std::make_unique 是 C++11 标准库中的一个实用函数,它是 C++14 标准中引入的,用于创建一个 std::unique_ptr 智能指针,并将其指向一个新分配...
编译CMAKE时报The std::unique_ptr错误 问题现象描述 编译CMAKE时报The std::unique_ptr错误,报错信息“CMake Error at CMakeLists.txt:92 (message): The C++ compiler does not support C++11 (e.g. std::unique_ptr).”。 关键过程、根本原因分析 此错误跟
// TEMPLATE FUNCTION make_uniquetemplate<class_Ty,class..._Types>inline typename enable_if<!is_array<_Ty>::value,unique_ptr<_Ty>>::typemake_unique(_Types&&..._Args){// make a unique_ptrreturn(unique_ptr<_Ty>(new_Ty(_STD forward<_Types>(_Args)...)));}template<class_Ty>inline ...
首先介绍std::make_unique,它是C++11标准库中的一个实用函数,用于创建一个std::unique_ptr智能指针,并将其指向一个新分配的对象。使用std::make_unique比直接使用new表达式更安全,因为它可以防止资源泄漏,并提供异常安全保证。接下来,我们将详细讨论std::unique_ptr,它是一个模板类,提供了对动态...
std::unique_ptr 是一种独占的语义,即只允许一个智能指针引用裸指针,这区别于 std::shared_ptr 允许多个 shared_ptr 引用同一个裸指针,它没有引用计数,它的性能比 shared_ptr 会高一点。
auto ptr3 = std::make_unique<MyClass>(42); return 0; } 在上述示例中,我们尝试使用已删除的默认构造函数创建unique_ptr对象,但由于该函数被删除,编译器会报错。正确的做法是使用带参数的构造函数来创建unique_ptr对象。 对于unique_ptr和make_unique的应用场景,它们通常用于管理动态分配的资源,如内存、文...
自己写一个make_unique的 比如make_uniquetemplate<typenameT,typename...Args>std::unique_ptr<T>make_unique(Args&& ...args){returnunique_ptr<T>(newT( std::forward<Args>(args)...)); } 指定析构器的工厂 usingnamespacestd;autodel = [](int* ptr) { ...
~unique_ptr() { delete _ptr; std::cout << "delete ptr" << "\n"; } T& operator*() { return *_ptr; } T* operator->() { return _ptr; } //C++11封拷贝 unique_ptr(const unique_ptr<T>& up) = delete; unique_ptr<T>& operator = (const unique_ptr<T>&up) = delete; pri...
unique_ptr在使用过程中主要注意的有两点,接下来进行介绍。 一、无法进行复制构造和赋值操作 unique_ptr没有copy构造函数,不支持普通的拷贝和赋值操作。 int main() { // 创建一个unique_ptr实例 unique_ptr<int> pInt(new int(666)); unique_ptr<int> pInt2(pInt); // 报错 ...
make_unique()是C++14引入的功能,但是可以广泛使用(也很容易自己写一个) Enforcement(实施建议) (Simple) Warn if a unique_ptr is constructed from the result of new rather than make_unique. (简单)如果unique_ptr从new得到的结果构建而不是使用make_uinque,报警。