我是智能指针的新手,我喜欢将它们用于共享对象的安全性和力量...
我有一个问题:如果我的班级使用一些经验法则(例如Big 5和Big 3)在其构造函数和析构函数中管理资源,我是否仍应使用智能指针?否则我的课可以代替他们。因为正如我在C ++ Primer 5 Edition中所读的那样,智能指针解决了原始指针所面临的问题,例如内存泄漏,双删除指针和访问悬空指针……我的课程可以避免这些问题:
class BallGame {
public:
using Resource = int;
BallGame(int);
BallGame(const BallGame&);
BallGame(BallGame&&);
BallGame& operator=(const BallGame&);
BallGame& operator=(BallGame&&);
~BallGame();
private:
Resource m_res;
};
考虑到我的班级成员正在做正确的事情,所以我可以避免使用智能指针吗?
我想知道某些情况下我应该使用智能指针而不是在班级中管理资源。
它们真的适用于“哑类”(定义构造函数,但行为不佳的析构函数的类),就像C ++入门书中的一样。
如果我在使用的每个类中为智能指针的内存所有权实现正确的语义,可以避免使用智能指针吗?
是,但是为什么呢?当您需要动态数组时,是否需要在每次需要时手动重新实现基本的std::vector
语义?我不这么认为。
int* ptr = new int[1024];
// oh my God! forgot to free it then welcome to memory leak
std::string* pStr = new std::string("Hello");
delete pStr;
//...
// and at some point in the program you think it is time to free pStr which has been already freed (among hundreds of code lines) then welcome to U.B.
std::cout << *pStr << std::endl; // pStr is a dangling pointer. U.B
使用智能指针解决此问题:
std::unique_ptr<int> upi = std::make_unique(7); // use upi effectively and don't care about freeing it because it automatically will be freed for you.