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

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

问题描述

C++ 中是否有一种通用的方式来表达参数的用法?我想隐式地告诉我的类的使用者他们传递的参数将如何被类使用.

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.

示例:

  1. 我拥有你的论点(会清理它)
  2. 我将在我有生之年保留对您论点的引用(因此您不应该在我活着的时候删除它)
  3. 我只会在构建过程中使用你的论点,不会引用

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

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 参数意味着该类将控制对象的内存管理.(我们用的不多.)

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 意味着该类可能会在很长一段时间内使用该参数,特别是可能会将其自己的 shared_ptr 存储到对象中.

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 - 普通引用意味着参数只会在调用期间使用.

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天全站免登陆