【发布时间】:2021-07-27 15:43:03
【问题描述】:
为了性能优化,我想利用字符串的引用而不是它的值。根据编译选项,我得到不同的结果。这种行为对我来说有点不清楚,我不知道导致这种差异的实际 gcc 标志。
我的代码是
#include <string>
#include <iostream>
const std::string* test2(const std::string& in) {
// Here I want to make use of the pointer &in
// ...
// it's returned only for demonstration purposes...
return ∈
}
int main() {
const std::string* t1 = test2("text");
const std::string* t2 = test2("text");
// only for demonstration, the cout is printed....
std::cout<<"References are: "<<(t1==t2?"equivalent. ":"different. ")<<t1<<"\t"<<t2<<std::endl;
return 0;
}
共有三种编译选项:
gcc main.cc -o main -lstdc++ -O0 -fPIC && ./main
gcc main.cc -o main -lstdc++ -O2 -fno-PIC && ./main
gcc main.cc -o main -lstdc++ -O2 -fPIC && ./main
前两个产生等效的结果(References are: different.),因此指针不同,但第三个产生等效的指针(References are: equivalent.)。
为什么会发生这种情况,我必须将哪个选项添加到选项-O2 -fPIC 以使指针再次变得不同?
由于此代码嵌入到更大的框架中,因此我无法删除选项-O2 或-fPIC。
由于我使用选项 -O2 和 -fPIC 获得了所需的结果,但是如果两个标志一起使用会出现不同的行为,我不清楚这些标志的确切行为。
我尝试使用 gcc4.8 和 gcc8.3。
【问题讨论】:
标签: c++ gcc compiler-flags