首页 > 学院 > 开发设计 > 正文

13.13

2019-11-14 11:09:24
字体:
来源:转载
供稿:网友

13.9 类里前面带~的函数,析构函数用来销毁对象释放资源,当没有定义自己的析构函数的时候编译器会自己定义合成析构函数。

13.10 智能指针的计时器会变为0,然后会释放智能指针指向的内存,然后销毁对象。 销毁对象,但是指针指向的内存不会被释放,因为是weak_ptr

13.11

#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) { } HasPtr& Operator=(const HasPtr& rhs){ if(this=&rhs) return this; delete ps; ps=new string (*rhs.ps); i=rhs.i; return *this; } ~HasPtr(){ delete ps; }PRivate: std::string *ps; int i;};

13.12 3次,离开函数的时候,accum,item1,item2会被析构。

13.13 @pezy

#include <iostream>#include <vector>#include <initializer_list>struct X { X() { std::cout << "X()" << std::endl; } X(const X&) { std::cout << "X(const X&)" << std::endl; } X& operator=(const X&) { std::cout << "X& operator=(const X&)" << std::endl; return *this; } ~X() { std::cout << "~X()" << std::endl; }};void f(const X &rx, X x){ std::vector<X> vec; vec.reserve(2); vec.push_back(rx); vec.push_back(x);}int main(){ X *px = new X; f(*px, *px); delete px; return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表