I created simple C++ std::string
values.
But the value has unexpected results.
I tested this code with g++ compiler (Linux) and Visual Studio (Windows) and both compilers show the same problem.
Normal result code
/* This code results are Normal */
#include <bits/stdc++.h>
int main() {
std::string a1 = "a1";
std::string a2 = "a2";
std::string b1("b1");
std::string b2("b2");
const char *c1 = std::string("c1").c_str();
const char *c2 = std::string("c2").c_str();
std::cout << "Expected [a1], real [" << a1 << "]\n";
std::cout << "Expected [a2], real [" << a2 << "]\n";
std::cout << "Expected [b1], real [" << b1 << "]\n";
std::cout << "Expected [b2], real [" << b2 << "]\n";
std::cout << "Expected [c1], real [" << c1 << "]\n";
std::cout << "Expected [c2], real [" << c2 << "]\n";
}
Console result:
Expected [a1], real [a1]
Expected [a2], real [a2]
Expected [b1], real [b1]
Expected [b2], real [b2]
Expected [c1], real [c1]
Expected [c2], real [c2]
Abnormal result code
/* This code results has some problem. */
#include <bits/stdc++.h>
int main() {
const char *c1 = std::string("c1").c_str();
const char *c2 = std::string("c2").c_str();
std::string a1 = "a1";
std::string a2 = "a2";
std::string b1("b1");
std::string b2("b2");
// const char *c1 = std::string("c1").c_str();
// const char *c2 = std::string("c2").c_str();
std::cout << "Expected [a1], real [" << a1 << "]\n";
std::cout << "Expected [a2], real [" << a2 << "]\n";
std::cout << "Expected [b1], real [" << b1 << "]\n";
std::cout << "Expected [b2], real [" << b2 << "]\n";
std::cout << "Expected [c1], real [" << c1 << "]\n"; // c1 = b2?
std::cout << "Expected [c2], real [" << c2 << "]\n"; // b2 = b2?
}
Console result:
Expected [a1], real [a1]
Expected [a2], real [a2]
Expected [b1], real [b1]
Expected [b2], real [b2]
Expected [c1], real [b2]
Expected [c2], real [b2]
I usually use only string str = ""
, but I was wondering when I was testing.
The constructor is expected to have a problem I think.
How can I understand this abnormal results with std::string?