?? schoen.txt
字號:
Strict Ownership in STL Containers
by Oliver Schoenborn
Listing 1:
struct A;
struct B {
A* a;
B(A*); // TBD 1
~B(); // TBD 2
}
struct A {
B* b;
A(): b(new B) {}
~A() {delete b;}
};
Listing 2:
// Foo.hh
class Bar;
class Foo {
public:
Foo();
void doSomething() const;
void getBar(DynObj<Bar>&);
private:
DynObj<Bar> _bar;
};
// Foo.cc
#include "Foo.hh"
#include "Bar.hh"
Foo::Foo(): _bar(new Bar) {}
void Foo::doSomething() const { _bar().constMethod(); }
void Foo::getbBar(DynObj<Bar>& bar) {_bar.giveAway(bar);}
// Bar.hh
class Bar {
public:
Bar() {}
void constMethod() const {}
};
// main.cc
int main() {
Foo foo;
foo.doSomething();
DynObj<Bar> bar;
foo.getBar(bar);
bar().constMethod();
}
Listing 3:
DynTmp<Foo> getFoo() {return new Foo;}
DynTmp<Foo> getFoo2() {
DynObj<Foo> foo(new Foo);
return foo.moveToTmp();
}
int main() {
DynObj<const Foo> foo( getFoo() );
getFoo2();
}
Listing 4:
class Foo {
public:
Foo() {}
RRef<Bar> getBar() const {return _bar;}
void reset() {_bar.reset();}
private:
DynObj<Bar> _bar;
};
int main() {
Foo foo;
RRef<const Bar> bar( foo.getBar() );
bar().constMethod(); // ok
foo.reset(); // destroys bar
bar().constMethod(); // assert fails
}
Listing 5:
struct Foo {
virtual void constMethod() const = 0;
virtual ~Foo() {}
};
struct DerFoo: Foo {
virtual void constMethod() const {}
};
int main() {
// instantiate list
typedef DynObj<Foo>::InValueContainer DOFoo;
std::list<DOFoo> foos;
// add two new DAO's
foos.push_back( dynObj(new DerFoo) );
foos.push_back( dynObj(new DerFoo) );
// add a DAO from a DynObj
DynObj<Foo> foo(new DerFoo);
foos.push_back( foo.giveAway() );
assert(foo.isNull()); // true
// xfer DAO from head of list
DynObj<const Foo> foo2( foos.begin()->giveAway() );
assert(foos.begin()->isNull()); // true
foo2().constMethod();
// erase first and second items
foos.erase(foos.begin());
foos.erase(foos.begin());
}
1
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -