该标准提供了一个模板特化std::unique_ptr,正确调用delete[]其析构函数:
void func()
{
std::unique_ptr< int[] > arr(new int[10]);
.......
}
Run Code Online (Sandbox Code Playgroud)
由于std::shared_ptr这种专业化不可用,因此有必要提供一个正确调用的删除器delete[]:
void func()
{
// Usage
shared_ptr array (new double [256], [](double* arr) { delete [] arr; } );
..............
}
Run Code Online (Sandbox Code Playgroud)
这只是一个疏忽吗?(以同样的方式存在std::copy_if)或是否有原因?
我尝试学习如何使用智能指针。我长期使用普通指针,我认为我需要升级我的技能。
我做了一些研究,我了解智能指针的某些方面,但我尝试在一个清晰的项目中实施,以了解智能指针是如何工作的。我尝试:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void print() { std::cout << "Message!"; }
};
int main()
{
std::shared_ptr<int>f1(new int[100]);
f1.get()[1] = 1;
std::cout << f1.get()[1];
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,消息是打印的。但是当我尝试:
#include <iostream>
#include <array>
#include <memory>
class Entity
{
public:
Entity()
{
std::cout << "Entity called!" << std::endl;
}
~Entity()
{
std::cout << "Entity destroyed!" << std::endl;
}
void …Run Code Online (Sandbox Code Playgroud)