在“现代 C++”中,指向作为类成员的对象的指针
因此,我听到的关于现代 C++ 风格的一条经验法则是,不需要使用 new 或 delete,而应该使用智能指针。那么,当我有一个类,其中一个成员是指向另一个对象的指针时,该如何解决这个问题。通过使用智能指针,我可以避免删除的需要,但我仍然需要使用 new 创建对象。例如,下面是“规范的”现代 C++ 风格,或者应该如何解决这个问题?
#include
#include
class B {
public:
B () { std::printf("constructing B\n");}
~B () { std::printf("destroying B\n");}
};
class A {
public:
A ()
{
std::printf("constructing A\n");
b = std::unique_ptr(new B());
}
~A () { std::printf("destroying A\n");}
private:
std::unique_ptr b;
};
int main()
{
A a;
return 0;
}
So one rule of thumb I've heard with respect to modern C++ style is that one shouldn't need to use new or delete, and one should instead use smart pointers. So how to go about this when I have a class where one of the members is a pointer to another object. By using a smart pointer I can avoid the need to delete, but I still need to create the object with new. E.g. is the below "canonical" modern C++ style, or how should one go about this?
#include
#include
class B {
public:
B () { std::printf("constructing B\n");}
~B () { std::printf("destroying B\n");}
};
class A {
public:
A ()
{
std::printf("constructing A\n");
b = std::unique_ptr(new B());
}
~A () { std::printf("destroying A\n");}
private:
std::unique_ptr b;
};
int main()
{
A a;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用
new
。使用new
并没有什么问题,只是应该尽可能少地使用它。(
delete
另一方面,几乎不应该使用,因为它的使用应该始终封装在某种 RAII 句柄中,如智能指针或容器。)当使用智能指针时,您应该始终将
new
的结果分配给指定的智能指针或使用reset
。在您的情况下,您需要使用:或:
或:
(为什么这很重要,请参阅
boost::shared_ptr
文档。)You use
new
. There's nothing wrong with usingnew
, it should just be used as rarely as possible.(
delete
on the other hand, should almost never be used, since its usage should always be encapsulated in some sort of RAII handle like a smart pointer or a container.)Note that when using smart pointers, you should always assign the result of
new
to a named smart pointer or usereset
. In your case, you'd want to use:or:
or:
(For why this is important, see the "Best Practices" section of the
boost::shared_ptr
documentation.)