在其构造函数中创建对象本身(此)的智能指针
因此,可以说我有
class A
{
A(std::vector<std::shared_pointer<A>> &a_vec)
{
auto shared_ptr = std::make_shared<A>(*this);
a_vec.pushback<shared_ptr>;
{
};
class B
{
std::vector<std::shared_pointer<A>> a_vector_;
void constructA()
{
created_A = make_shared<A>(a_vector_);
}
}
IM为B创建一种创建A的方法,该方法会创建A,并且A将其推向向量B提供的方法。
从表面上看,这种依赖性像我期望的那样起作用,至少我认为直到我意识到a_vec.pushback&lt; this*&gt ;;
不是很可靠。
当我在推送和共享指针初始化之间有更多代码时,
A(std::vector<std::shared_pointer<A>> a_vec)
{
auto shared_ptr = std::make_shared<A>(*this);
//insert more code here
a_vec.pushback<shared_ptr>;
{
似乎我在那里所做的初始化和其他事情并没有反映在共享指针指向的指针上。原因是什么原因,有没有办法解决它?还有一个原因,这是一种不良的习惯吗?
So lets say I have
class A
{
A(std::vector<std::shared_pointer<A>> &a_vec)
{
auto shared_ptr = std::make_shared<A>(*this);
a_vec.pushback<shared_ptr>;
{
};
class B
{
std::vector<std::shared_pointer<A>> a_vector_;
void constructA()
{
created_A = make_shared<A>(a_vector_);
}
}
So Im creating a method for B which creates an A and the A pushes itself to the vector B provides.
And on paper this dependancy works like I expected to, atleast I thought it was until I realised the a_vec.pushback<this*>;
is not very dependable.
When I have more code inbetween the push and the shared pointer initialisation as such
A(std::vector<std::shared_pointer<A>> a_vec)
{
auto shared_ptr = std::make_shared<A>(*this);
//insert more code here
a_vec.pushback<shared_ptr>;
{
It seems that the initialisations and other stuff I do in there isn't reflected to the pointer the shared pointer is pointing. Whats the cause of this and is there a way to fix it? Also is there a reason this would be a bad practice to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在C ++中编程时,挑战之一是了解对象寿命。因此,最好使对象创建和破坏尽可能清晰。
据我了解,您的案例是记忆“自动”所有创建的对象。 进行更容易
使用“工厂方法”构建体[错误路径]
可以制作了解共享_ptr/feek_ptr的对象:使用模板std :: enable_shared_from_this。
在这种情况下,您的代码可能会遵循:
但是错误,因为仅在函数
make_shared
执行基础feek_ptr才能“准备就绪”,仅在施工呼叫后才执行。调用
shared_from__this
或feek_from__from_this
仅在执行make_shared
函数之后才有效。One of the challenges when you are programming in C++ is to understand object lifetime. So it is better to make object creation and destruction as clear as possible.
As I understood your case is to memoize "automagically" all created objects. It is easier to do using "factory method" constructA
[WRONG PATH]
It is possible to make object which aware of shared_ptr/weak_ptr: use template std::enable_shared_from_this.
In that case your code might be following,:
BUT it wrong, because underlying weak_ptr is "ready" only after function
make_shared
is executed, means only after construction call.Calling
shared_from_this
orweak_from_this
is valid only aftermake_shared
function is executed.