C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 智能指针是否可以选择性地隐藏或重定向对它们包装的对象的函数调用?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个项目,其中某些对象被引用计数 – 它与COM的设置非常相似.无论如何,我们的项目确实有智能指针,可以减少为这些对象显式调用Add()和Release()的需要.问题是,有时,开发人员仍然使用智能指针调用Release().

我正在寻找的是一种从智能指针调用Release()创建编译时或运行时错误方法.编译时似乎不可能.我以我有一个运行时解决方案(见下面的代码),但它也没有完全编译.显然,使用operator->()后不允许隐式转换.

无论如何,任何人都可以想到一种方法来完成我想要完成的任务吗?

非常感谢您的帮助!

凯文

#include <iostream>
#include <Cassert>

using namespace std;

class A
{
public:
    void Add()
    {
        cout << "A::Add" << endl;
    }

    void Release()
    {
        cout << "A::release" << endl;
    }

    void Foo()
    {
        cout << "A::Foo" << endl;
    }
};

template <class T>
class MysmartPtrHelper
{
    T* m_t;

public:

    MysmartPtrHelper(T* _t)
        : m_t(_t)
    {
        m_t->Add(); 
    }

    ~MysmartPtrHelper()
    {
        m_t->Release(); 
    }

    operator T&()
    {
        return *m_t;
    }

    void Add()
    {
        cout << "MysmartPtrHelper::Add()" << endl;
        assert(false);
    }

    void Release()
    {
        cout << "MysmartPtrHelper::release()" << endl;
        assert(false);
    }
};

template <class T>
class MysmartPtr
{
    MysmartPtrHelper<T> m_Helper;

public:

    MysmartPtr(T* _pT)
        : m_Helper(_pT)
    {
    }

    MysmartPtrHelper<T>* operator->()
    {
        return &m_Helper;
    }
};

int main()
{
    A a;

    MysmartPtr<A> pA(&a);

    pA->Foo(); // this currently fails to compile.  The compiler
               // complains that MysmartPtrHelper::Foo() doesn't exist.

    //pA->Release(); // this will correctly assert if uncommented.

    return 0;
}

解决方法

你不能这样做 – 一旦你超载了操作符 – >你被卡住了 – 重载的运算符会以同样的方式运行,而不管它是什么.

您可以将Add()和Release()方法声明为private,并使智能指针成为引用计数类的朋友.

大佬总结

以上是大佬教程为你收集整理的c – 智能指针是否可以选择性地隐藏或重定向对它们包装的对象的函数调用?全部内容,希望文章能够帮你解决c – 智能指针是否可以选择性地隐藏或重定向对它们包装的对象的函数调用?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。