#include <iostream> #include <memory> struct C { int a; int b; }; int main() { std::shared_ptr<C> foo; std::shared_ptr<C> bar(new C); foo = bar; foo->a = 10; bar->b = 20; if (foo) std::cout << "foo: " << foo->a << ' ' << foo->b << '\n'; if (...
struct destination;//连接的对象struct connection; //连接需要的信息connection connect(destbination*); //打开连接void disconnect(connection); //关闭连接void f(destination &d){connection c=connect(&d);//打开一个连接...//使用这个连接//如果在f函数退出之前忘记调用disconnect函数,那么该连接就没有关闭}...
struct Base{ std::string m_str; Base(std::string s): m_str(s) { std::cout<<"Base ctor:"<<m_str<<std::endl; } ~Base() { std::cout<<"Base dtor:"<<m_str<<std::endl; } }; struct Derived: public Base{ Derived(std::string s): Base(s) { std::cout<<"Derived ctor:"...
shared引用计数和weak引用计数的计数区域实际最终应该长这个样子: structSharedPtrControlBlock{intshared_count;intweak_count;};//大概长这个样子(简化版)template<classT>classweak_ptr{T* ptr;SharedPtrControlBlock* count;}; 针对空悬指针问题# 空悬指针问题是指:无法知道指针指向的堆内存是否已经释放。 得益于...
智能指针最大的一个陷阱是循环引用,循环引用会导致内存泄漏。解决方法是AStruct或BStruct改为weak_ptr structAStruct;structBStruct;structAStruct{std::shared_ptr<BStruct> bPtr; ~AStruct() {cout<<"AStruct is deleted!"<<endl; } };structBStruct{std::shared_ptr<AStruct> APtr; ...
structconnection;//连接需要的信息 connectionconnect(destbination*);//打开连接 voiddisconnect(connection);//关闭连接 voidf(destination&d) { connectionc=connect(&d);//打开一个连接 ...//使用这个连接 //如果在f函数退出之前忘记调用disconnect函数,那么该连接就没有关闭 }...
#include<memory>#include<iostream>struct Foo{Foo(){std::cout<<"Foo...\n";}~Foo(){std::cout<<"~Foo...\n";}};structD{voidoperator()(Foo*p)const{std::cout<<"Call delete from function object...\n";deletep;}};intmain(){{std::cout<<"constructor with no managed object\n";std...
但是,我自定义的一个 struct 也会导致崩溃,而这个 struct 有 48 个字节,调试到这,感觉这个 bug 越来越诡异了。 按理来说,在 C++ 里面,普通的结构体如果没有虚函数的话和自带的数据类型是完全相同的,都是一个内存地址,对应着其大小的字节流,但是在这,不同大小的类型竟然有不同的反应。
#include<iostream>#include<memory>usingnamespacestd;// Define a singly linked list nodestructNode{intdata;shared_ptr<Node> next; Node(intval) : data(val) , next(NULL) { } };classLinkedList{public: LinkedList() : head(NULL) { }// Insert a new node at the end of the linked listvoid...
structdestination;// 表示我们正在连接什么structconnection;// 使用连接所需的信息connectionconnect(destination*);//打开连接voiddisconnect(connection);// 关闭给定的连接voidf(destination&d/* 其他参数 */){//获得一个连接;记住使用完后要关闭它connection c=connect(&d);// 使用连接// 如果我们在 f 退出前...