我正在尝试使用循环引用boost::shared_ptr,并设计了以下示例:
class A{ // Trivial class
public:
i32 i;
A(){}
A(i32 a):i(a){}
~A(){
cout<<"~A : "<<i<<endl;
}
};
shared_ptr<A> changeI(shared_ptr<A> s){
s->i++;
cout<<s.use_count()<<'\n';
return s;
}
int main() {
shared_ptr<A> p1 = make_shared<A>(3);
shared_ptr<A> p2 = p1;
shared_ptr<A> p3 = p2;
shared_ptr<A> p4 = p3;
p1 = p4; // 1) 1st cyclic ref.
cout<<p1.use_count()<<'\n';
p1 = changeI(p4); // 2) 2nd cyclic ref.
cout<<p1.use_count()<<'\n';
// putchar('\n');
cout<<endl;
}
Run Code Online (Sandbox Code Playgroud)
哪个输出
4
5
4
~A : 4
Run Code Online (Sandbox Code Playgroud)
是不是我误解了所提到的循环引用boost::shared_ptr?因为,我预计间接引用的不同输出思维p1 …
我们在C++中进行了const非const函数重载,如此处所述,并在STL迭代器中使用.
我们在Java和C#中有这样的方法重载吗?
在以下代码段中:
shared_ptr<int> p;
{
p = shared_ptr<int>(new int);
cout<<p.use_count()<<endl;
}
cout<<p.use_count()<<endl;
Run Code Online (Sandbox Code Playgroud)
输出结果是
1 1
我不明白为什么第一个输出是1- 不应该是2?
为什么声明const int8_t* cstr = "asdf";会出错
invalid conversion from ‘const char*’ to ‘const int8_t*’
是不是int8_t*和char*一样吗?我在这里错过了一些微妙的东西吗?!
考虑两个班级
class A{
public:
int i;
A(){}
explicit A(const int ii):i(ii){}
virtual ~A(){
cout<<"~A - "<< i <<endl;
}
virtual void inc(){
i++;
cout<<"i: "<<i<<endl;
}
};
class B: public A{
public:
int j;
B(){}
explicit B(const int jj, const int ii=-1):A(ii), j(jj){}
~B(){
cout<<"~B - "<<i<<", "<<j<<endl;
}
void inc(){
A::inc();
j++;
cout<<"j: "<<j<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)
现在我们可以这样做main():
A *pa = new B();
//...
pa->inc(); // implements B::inc();
Run Code Online (Sandbox Code Playgroud)
现在使用boost库的版本
boost::shared_ptr<A> pa = boost::make_shared<B>(2);
//...
pa->inc(); // …Run Code Online (Sandbox Code Playgroud) c++ ×4
shared-ptr ×2
c# ×1
char-pointer ×1
const ×1
inheritance ×1
java ×1
make-shared ×1
overloading ×1
weak-ptr ×1