智能指针,typedef和转发声明 [英] smart pointers, typedefs and forward declarations
问题描述
我喜欢使用智能指针,并看到一些代码,使得很好地利用 typedef
使它们更漂亮。例如:
I love using smart pointers, and have seen a bit of code which makes nice use of typedef
s make make them prettier. For example:
struct A {
typedef boost::shared_ptr<A> pointer;
};
允许我写: A :: pointer a(new A);
但我在我的 typedef
正向声明...
But I have hit a minor snag in my typedef
happiness :-/, forward declarations...
所以想象这个场景:
struct B;
struct A {
boost::shared_ptr<B> b_;
};
struct B {
boost::shared_ptr<A> a_;
};
工作得很好,但我想清理一点。不幸的是,这是不起作用
works well enough, but I'd love to clean that up a little. Unfortunately, this is doesn't work
struct B;
struct A {
typedef boost::shared_ptr<A> pointer;
B::pointer b_; // <-- error here
};
struct B {
typedef boost::shared_ptr<B> pointer;
A::pointer a_;
};
我理解为什么,在文件中的那一刻,编译器没有B实际上有一个类型为指针
。
我有一种感觉,
推荐答案
使用typedefs不会使它更漂亮一些东西,但我很想听到一些聪明的想法。它是毫无价值的。您可以对不完整的类型创建 shared_ptr
,因此只需使用 shared_ptr< B>
。
That use of typedefs doesn't make it prettier- it's worthless. You can make a shared_ptr
to an incomplete type, so just use shared_ptr<B>
.
这篇关于智能指针,typedef和转发声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!