⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 schoen.txt

📁 用C++编的小程序。
💻 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 + -