引用部分内容来源:https://blog.csdn.net/qq_51931826/article/details/127059182?spm=1001.2014.3001.5502
关于c++ primer 第五版拷贝构造函数的问题
#include <string>
class HasPtr {
public:
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { }
HasPtr(const HasPtr& hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
private:
std::string *ps;
int i;
};
//或者
HasPtr(const HasPtr & h)
{
i = h.i;
ps = new string(*h.ps);
}
在上面的代码中,我在vs编辑的时候,发现如果定义如下:
HasPtr(const HasPtr & h)
{
i = h.i;
ps (h.ps = new string);
}
是否跟上面的答案等价呢,vs并运行检测没有报错,我觉得是等价第二种形式,不知道是否正确?