英文:
Using `volatile` has unexpected results
问题
我对尝试复制不同的错误时发现的以下差异感到困惑。此程序按预期工作:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<const char *>(s.c_str());
std::cout << *(p.get());
return 0;
}
它打印:
Hi
Hi
但是添加单个volatile
关键字:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<volatile const char *>(s.c_str());
std::cout << *(p.get());
return 0;
}
会使其打印:
Hi
1
这也没有帮助:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<volatile const char *>(reinterpret_cast<volatile const char *>(s.c_str()));
std::cout << *(p.get());
return 0;
}
为什么?
英文:
I am puzzled by following difference discovered by trying to replicate different bug. This program works as expected:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<const char *>(s.c_str());
std::cout << *(p.get());
return 0;
}
It prints
Hi
Hi
But adding single volatile
keyword:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<volatile const char *>(s.c_str());
std::cout << *(p.get());
return 0;
}
makes it print:
Hi
1
This did not help either:
#include <memory>
#include <string>
#include <iostream>
int main() {
std::string s = "Hi\n";
std::cout << s;
auto p = std::make_unique<volatile const char *>(reinterpret_cast<volatile const char *>(s.c_str()));
std::cout << *(p.get());
return 0;
}
Why?
答案1
得分: 4
std::ostream
对const char*
和bool
(指针可以转换为bool
)重载了运算符<<
,但没有重载volatile const char*
。
然后,可以通过以下方式简单复制差异:
#include <iostream>
int main() {
/*volatile*/ const char * s = "abc\n";
std::cout << s;
return 0;
}
取消注释volatile
后,输出为abc
,注释它后输出为1
(没有换行符)。
英文:
The answer is in the comment by Jarod42:
> std::ostream
has overload for operator <<
for const char*
and bool
(pointer has conversion to bool
), not for volatile const char *
The difference then can be replicated simply by:
#include <iostream>
int main() {
/*volatile*/ const char * s = "abc\n";
std::cout << s;
return 0;
}
Gives abc
with volatile
commented out and 1
(without newline) with uncommenting it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论