c++ - 如何理解C++ primer 3rd中的句子

标签 c++ abstract-class information-hiding inline-functions

以下摘自 <C++ primer (3rd)> 的第 7.6 章作者:Stanley B. Lippman Josée Lajoie。

A function specified as inline is expanded "in line" at each point in the program in which it is invoked. For example,

int minVal2 = min( i, j );

is expanded during compilation into

int minVal2 = i < j ? i : j;

The run-time overhead of making min() a function is thus removed. min() is declared inline by specifying the inline keyword before the function's return type in the function declaration or definition:

inline int min( int v1, int v2 ) { /* ... */ }

Note, however, that the inline specification is only a recommendation to the compiler. The compiler may choose to ignore this recommendation, because the function declared inline is not a good candidate for expansion at the point of call. A recursive function, such as rgcd(), for example, cannot be completely expanded at the point of call (although its first invocation can). A 1,200-line function is also likely not to be expanded at the point of call. In general, the inline mechanism is meant to optimize small, straight- line, frequently called functions. It is of primary importance in the support of information hiding in the design of abstract data types, such as the IntArray class introduced in Section 2.3 with its size() inline member function.

有人可以解释一下标记为粗体的句子吗?

最佳答案

我这里没有第 3 版的全文,但从你发布的上下文来看,他说的很清楚。

想象一种“vector ”类。

class Vector {
private: 
  int * data; // pointer to data

它可以通过多种方式提供对 vector 大小的访问:

选择一:公共(public)成员变量:

public:
  int datasize; 

选择 2:具有公共(public)访问器的私有(private)变量

private:
  int datasize; 

public:
  int getSize(); // body can be hidden in CPP, but would be { return datasize;};

选择 3:与 2 相同,但带有内联访问器

private:
  int datasize; 

public:
  inline int getSize() { return datasize; };

现在,#1 的数据隐藏很差,但性能很好。 #2 有很好的数据隐藏,但性能很差。 #3 具有良好的数据隐藏能力,并且可能具有出色的性能。 (记住内联只是一个提示)

在我看来,#3 的数据隐藏略逊于 #2,因为函数代码显示在 header 中 - 即使您无法访问该成员。所以,我会按照...重写他的陈述。

Inline Functions provide a good compromise between the requirements of Data Hiding versus Performance.

我不同意它是“最重要的”,因为它只是对编译器的提示。

关于c++ - 如何理解C++ primer 3rd中的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13266672/

相关文章:

c++ - C++ 示例 "Memory barrier"

c++ - 无法解析标识符 __PRETTY_FUNCTION__

java - 在 Java 中克隆对象 [3 个问题]

html - 隐藏表单输入字段以防止使用 firebug 访问的最佳方法?

encryption - 用一次一密编码的信息能否与随机噪声区分开来?

c++ - 检查流是否以换行符结尾

c++ - 不满意链接错误 : undefined symbol _ZN5boost6system16generic_categoryEv in java (JNI)

Python抽象调用基类中导入的库的正确方法

java - 确保对某种类型的所有已声明和继承的成员调用方法

abstraction - 信息隐藏与隐藏的依赖关系