C++ 返回空智能指针
我有一节课看起来像这样C++ 返回空智能指针,c++,C++,我有一节课看起来像这样 class A { std::shared_ptr<Type> ret; public: A() { ret=std::shared_ptr<Type>(new Type); } std::shared_ptr<Type> GetTypeA(){return ret;} A (const A&a) { .... ret=a.ret; } }; cla
class A
{
std::shared_ptr<Type> ret;
public:
A()
{
ret=std::shared_ptr<Type>(new Type);
}
std::shared_ptr<Type> GetTypeA(){return ret;}
A (const A&a)
{
....
ret=a.ret;
}
};
class Type
{
A aa;
public:
Type(A*a):aa(*a){}
};
A类
{
std::共享_ptr ret;
公众:
()
{
ret=std::共享ptr(新型);
}
std::shared_ptr GetTypeA(){return ret;}
A(常数A&A)
{
....
ret=a.ret;
}
};
类类型
{
A aa;
公众:
类型(A*A):aa(*A){
};
在客户机代码的某个地方,我像这样调用GetTypeA方法
void func(A*pA)
{
...
std::shared_ptr<Type> spT=pA->GetTypeA();
...
}
void func(A*pA)
{
...
std::shared_ptr spT=pA->GetTypeA();
...
}
调试显示调用后
spT=empty
。但是在pA
内部,ret
值不是空的。我注意到您的代码中有一些错误:
A()
{
ret=std::shared_ptr<Type>(new Type);
}
问题是它没有解决“递归方面”,根据您的需要,我会在类型类中使用对a的静态引用…Post a
类a的复制构造函数在哪里?@Jagannath我更新了我的帖子。请重新阅读。您希望如何默认构造类型?参见<代码> A/CODE创建一个新的<代码>类型和<代码>类型< /COD>按值保存<代码> A/COD>,这看起来是递归依赖性。@ DavidCattor,您自己在C++中解决了:
class Type
{
A* aa; // Use a pointer
public:
Type::Type(A&a) :aa(&a){} // Use references
};