【发布时间】:2015-04-23 19:58:14
【问题描述】:
#include <iostream>
using namespace std;
template<class C>
class Bar
{
public:
Bar(C& c) : _c(c) {};
~Bar(){};
private:
C& _c;
};
class Foo
{
public:
Foo() : bar(this) {}; //instead of bar(*this)
~Foo(){};
private:
Bar<Foo> bar;
};
int main() {
// your code goes here
Foo f;
return 0;
}
我想通过引用在Foo 上模板化的类Bar 来传递this 指针。如果我不想在构造 bar 时取消引用 this 的语法是什么?
ideone链接:http://ideone.com/jGviBM
【问题讨论】:
-
为什么要这样做?另外,为什么不存储 C* 而不是 C& 并接受 C* 作为构造函数的参数?
-
这将是危险的,不管你怎么做,有时会看到一个部分建造或部分破坏的物体......
-
@Maria 对于这种特殊的设计,我宁愿引用 C 而不是指针,因为
Bar的不同实现可能会在各种不同的事物上对其进行模板化。我想在这种情况下使用引用来避免处理 NULL 指针的情况。 @aschepler:你是什么意思?能详细点吗? -
this不能是nullptr,因此您始终可以在调用方安全地取消引用它。 -
@armundle 另外,我认为您将在这里进行某种循环删除。例如,在 Foo 上调用 delete,它会删除 Bar,然后尝试删除相同的 Foo。这真的很危险。如果要以这种方式使用 bar,则必须让 C& 成为 C*。