小智 7
当你不需要他们,不使用指针不使用拥有原始指针(除非你有一个非常好的理由来让他们).
使用自动存储时间:
std::list<char> stuff;
thing object{stuff};
Run Code Online (Sandbox Code Playgroud)
构造函数thing将std::list<char>作为其参数:
#include <utility> // for std::move
class thing {
public:
explicit thing(std::list<char> stuff_) : stuff(std::move(stuff_)) {}
private:
std::list<char> stuff;
};
Run Code Online (Sandbox Code Playgroud)
如果你这样做,析构函数thing将在thing超出范围时调用,隐式调用析构函数stuff.许多优秀的C++书籍都非常详细地解释了这一点.
与Objective-C不同,C++使用RAII而不是引用计数.基本规则是:尽可能使用自动存储持续时间,避免原始拥有指针,new除非你有充分的理由否则不要使用.