C++ 这不是无用的内联声明吗?
C++ Isn't this a useless inline declaration?
这是另一个关于内联函数的问题。
但我会立即接受可能的评论和答案:
- 在 class 中定义函数使其自动内联。
- 通过使用内联标记函数可以实现相同的行为
在 class.
之外
- 内联函数不一定是内联的。这是
完全由编译器将其内联。
现在,我的问题:
内联函数意味着将函数体复制到调用它的地方。
假设编译器在访问私有或受保护成员时不会将其内联是不是正确的?
该程序实际上无法访问成员,对吗?
我想知道这一点,因为对我来说,如果有人内联一个 显然 无法内联的函数,那一定看起来很奇怪。
这是一个例子:
//Declaration
class Controller
{
public:
bool bHasTarget();
private:
const Object* pTarget;
};
//Definition
inline bool Controller::bHasTarget(){
return !(pTarget == nullptr); //<- This cannot be inlined...Can it?
}
An inline function may not be inlined by the compiler. It is completly up to the compiler to inline it.
编译器可能内联,但也可能不会。不能保证。
Isn't it right to assume that the compiler will not inline it if it accesses private or protected members?
不,这样假设是不对的。访问私有或受保护成员不会阻止内联。
The programm would literally not be able to access the members right?
该程序确实能够访问私有成员和受保护成员。该函数是成员,无论是否内联。
更详细地说,编译器会在进行任何内联优化之前检查程序是否违反了访问规则。检查通过后,访问说明符对生成的程序意义为零,不限制任何优化。
示例函数可以内联。
编译器可以访问一切。这些限制只对程序员有效。这意味着 Compiler 没有限制访问任何变量!最后,每个变量都被翻译成一个可以访问的地址。所以对于编译器来说,内联你提供的代码是没有问题的!
还有一些 "cheats" 可以作为程序员访问私有变量。例如
struct foo
{
private:
int a;
int b;
};
...
foo test;
int *cheat = reinterpret_cast<int*>(&test);
cheat[0] = 1; //This would Change a
...
这是另一个关于内联函数的问题。
但我会立即接受可能的评论和答案:
- 在 class 中定义函数使其自动内联。
- 通过使用内联标记函数可以实现相同的行为 在 class. 之外
- 内联函数不一定是内联的。这是 完全由编译器将其内联。
现在,我的问题:
内联函数意味着将函数体复制到调用它的地方。
假设编译器在访问私有或受保护成员时不会将其内联是不是正确的?
该程序实际上无法访问成员,对吗?
我想知道这一点,因为对我来说,如果有人内联一个 显然 无法内联的函数,那一定看起来很奇怪。
这是一个例子:
//Declaration
class Controller
{
public:
bool bHasTarget();
private:
const Object* pTarget;
};
//Definition
inline bool Controller::bHasTarget(){
return !(pTarget == nullptr); //<- This cannot be inlined...Can it?
}
An inline function may not be inlined by the compiler. It is completly up to the compiler to inline it.
编译器可能内联,但也可能不会。不能保证。
Isn't it right to assume that the compiler will not inline it if it accesses private or protected members?
不,这样假设是不对的。访问私有或受保护成员不会阻止内联。
The programm would literally not be able to access the members right?
该程序确实能够访问私有成员和受保护成员。该函数是成员,无论是否内联。
更详细地说,编译器会在进行任何内联优化之前检查程序是否违反了访问规则。检查通过后,访问说明符对生成的程序意义为零,不限制任何优化。
示例函数可以内联。
编译器可以访问一切。这些限制只对程序员有效。这意味着 Compiler 没有限制访问任何变量!最后,每个变量都被翻译成一个可以访问的地址。所以对于编译器来说,内联你提供的代码是没有问题的!
还有一些 "cheats" 可以作为程序员访问私有变量。例如
struct foo
{
private:
int a;
int b;
};
...
foo test;
int *cheat = reinterpret_cast<int*>(&test);
cheat[0] = 1; //This would Change a
...