通过方法接口表达C ++参数的用法 [英] Express the usage of C++ arguments through method interfaces

查看:110
本文介绍了通过方法接口表达C ++参数的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种常见的方式来表达在C ++中的参数的用法?我想隐式告诉我的类的消费者他们传递的参数将被类使用。



示例:


  1. 我拥有您的参数/ li>
  2. 我会在生命期间提及你的论点(所以你不应该在我活着的时候删除它)



  3. 有没有一种常见的方法来简单地使用方法声明来表达这些东西?我认为在第一种情况下,std :: auto_ptr会有意义。在第二种情况下,我通常使用一个指针,以避免有人从堆栈传递一个值,这会使我的引用快速失效,或者一个shared_ptr。在第三种情况下,我参考允许栈中的值。



    如何处理这个?还有必要依赖于智能指针在这里,或者可以通过使用裸体引用和指针以某种方式表达这样的事情?

    解决方案

    我们的团队拥有与您建议的类似的编码约定:



    1 - auto_ptr参数意味着该类将控制对象的内存管理。 (我们不用这么多。)



    2 - shared_ptr意味着类可能会使用参数一段延长的时间,特别是可以存储off它自己对该对象的shared_ptr。



    3 - 平原引用意味着该参数将只在调用期间使用。



    我们将其视为编码标准。这不是我们为每一个电话记录的。


    Is there a common way to express the usage of arguments in C++? I want to implicitly tell the consumers of my class how the arguments they pass will be used by the class.

    Examples:

    1. I own your argument (will clean it up)
    2. I will hold a reference to your argument during my lifetime (so you should NOT delete it while I'm stile alive)
    3. I will use your argument only during construction and won't hold a reference

    Is there a common way to express these things simply using the method declaration? I think in the first case a std::auto_ptr would make sense. In the second case I usually take a pointer to avoid someone passing a value from the stack which would invalidate my reference quickly, or alternatively a shared_ptr. In the third case I take a reference to allow values from the stack.

    How do you deal with this? Also is it necessary to rely on smart pointers here, or can one express such things simply by using naked references and pointers somehow?

    解决方案

    Our team has similar coding conventions to the ones you suggest:

    1 - auto_ptr argument means that the class will take control of memory management for the object. (We don't use this much.)

    2 - shared_ptr means that the class will probably use the argument for an extended period of time, and in particular may store off its own shared_ptr to the object.

    3 - Plain reference means that the argument will only be used for the duration of the call.

    We treat this as a coding standard. It isn't something we document for each and every call.

    这篇关于通过方法接口表达C ++参数的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆