我最近学习了constexpr
函数,我编写了一个函数,通过检查它们的地址来检查两个字符串是否是同一个对象(仅仅是为了好奇)。函数编译正确,但是当我尝试调用该函数时似乎发生了一些问题。
理论上,如果函数的参数是常量表达式,函数将返回一个常量表达式,否则,它将像普通函数一样运行。所以在代码的第一部分,我尝试用const变量调用该函数。在第二部分中,我用非const变量调用函数。
以下是我的代码。我使用Visual Studio Community 2015.编译器警告我有两个我在下面用^
标记的错误,但代码仍然可以编译和运行。
#include <iostream>
#include <string>
constexpr bool isSameString(const std::string &s1, const std::string &s2) {
return &s1 == &s2;
}
int main() {
//constexpr std::string s("p"); // No constexpr constructor
static const std::string s1("a");
static const std::string s2("a");
static const std::string s3("b");
// Right return value in editor, wrong when running.
constexpr bool b1 = isSameString(s1, s1);
// Error in editor(but can still compile), wrong when running.
constexpr bool b2 = isSameString(s1, s2);
// ^^^^^^^^^^^^ Error
// Error in editor(but can still compile), wrong when running.
constexpr bool b3 = isSameString(s1, s3);
// ^^^^^^^^^^^^ Error
std::cout << b1 << " " << b2 << " " << b3 << std::endl;
/********************************************************************/
std::string s4("x");
std::string s5("x");
std::string s6("y");
std::cout << isSameString(s4, s4) << " " // Right return value
<< isSameString(s4, s5) << " " // Right return value
<< isSameString(s4, s6) << std::endl; // Right return value
std::cin.get();
}
所以,
b1
的值不同?constexpr
?如果有人能帮助我,我将不胜感激:)
修改
我知道std::string
不是文字类型,但引用是文字类型。问题是关于如何使用constexpr
功能。所以我认为它与this question没有重复。