I'm learning about constexpr
function recently, and I write a function to check if two strings are the same object by examining their address (just for curiosity). The function compiled correctly, but it seems some problem happened when I try to call that function.
Theoretically, the function will return a constant expression if its arguments are constant expressions, otherwise, it will act like a normal function. So in the first part of the code, I try to call the function with const variables. In the second part, I call the function with nonconst variables.
Below is my code. I use Visual Studio Community 2015. The compiler warned me with two errors that I marked with ^
below, but the code can still be compiled and run.
#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();
}
So,
- Are there any ways to fix these two errors?
- Why is the code can still be compiled and run with these errors?
- Why the value of
b1
is different between in editor and when running? - Are there any ways to correctly call the function that return a
constexpr
?
I'd be grateful if anyone can help me :)
EDIT
I know that the std::string
is not a literal type, but a reference is a literal type. And the question is about how to use constexpr
function. So I think it's not duplicated with this question.