gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:23:38 25 4
gpt4 key购买 nike

以下摘自 <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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com