[英]Pointers to object as class member in “modern C++”
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. 因此,我听说过有关现代C ++风格的一条经验法则是,不必使用new或delete,而应该使用智能指针。 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.
通过使用智能指针,可以避免删除操作,但是仍然需要使用new创建对象。 Eg is the below "canonical" modern C++ style, or how should one go about this?
例如下面的“规范”现代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;
}
You use new
. 您使用
new
。 There's nothing wrong with using new
, it should just be used as rarely as possible. 使用
new
没什么错,应该尽可能少地使用它。
( 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.) (另一方面,几乎不应该使用
delete
,因为它的用法应始终封装在某种RAII句柄中,例如智能指针或容器。)
Note that when using smart pointers, you should always assign the result of new
to a named smart pointer or use reset
. 请注意,使用智能指针时,应始终将
new
的结果分配给已命名的智能指针或使用reset
。 In your case, you'd want to use: 对于您的情况,您想使用:
A() : b(new B()) { }
or: 要么:
A()
{
std::unique_ptr<B> x(new B());
b = std::move(x);
}
or: 要么:
A() { b.reset(new B()); }
(For why this is important, see the "Best Practices" section of the boost::shared_ptr
documentation .) (有关为什么这很重要的信息,请参见
boost::shared_ptr
文档的“最佳实践”部分。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.