从升级当我遇到一个问题#include <experimental/filesystem>来#include <filesystem>.似乎该std::filesystem::path::wstring方法没有返回与中相同的字符串experimental::filesystem.我编写了以下小测试程序,其中包含输出结果.
#include <iostream>
#include <filesystem>
#include <experimental/filesystem>
namespace fs = std::filesystem;
namespace ex = std::experimental::filesystem;
using namespace std;
int main()
{
fs::path p1{ L"C:\\temp/foo" };
wcout << "std::filesystem Native: " << p1.wstring() << " Generic: " << p1.generic_wstring() << endl;
ex::path p2{ L"C:\\temp/foo" };
wcout << "std::experimental::filesystem Native: " << p2.wstring() << " Generic: " << p2.generic_wstring() << endl;
}
/* Output:
std::filesystem Native: C:\temp/foo Generic: C:/temp/foo
std::experimental::filesystem Native: C:\temp\foo …Run Code Online (Sandbox Code Playgroud) 我使用Visual Studio 2017版本15.3.1测试了以下代码.
v.push_back(std::move(str1))按预期工作.它将内容移动str1到矢量中.
str2是一个常量字符串.由于常量字符串在创建后无法修改,因此我希望该v.push_back(std::move(str2))语句会导致编译器警告.但令我惊讶的是,没有编译器警告.走进它后,我发现push_back(const T&)实际上已经调用了过载.该std::move中std::move(str2)似乎没有任何效果.
我的问题:是否应该在尝试移动常量对象时发出编译器警告?
// Compiled with Visual Studio 2017 version 15.3.1
std::vector<std::string> v;
std::string str1 = "string 1";
v.push_back(std::move(str1));
// Call push_back(T&&). The contents of str1 is moved into the vector.
// This is less expensive, but str1 is now valid but unspecified.
const std::string str2 = "string 2";
v.push_back(std::move(str2));
// Call push_back(const T&). A copy of str2 is added into the vector.
// …Run Code Online (Sandbox Code Playgroud) 我有一个永远的线程循环调用std::this_thread::sleep_for延迟10毫秒.持续时间是临时对象std::chrono::milliseconds(10).一些示例代码后,延迟调用似乎是"正常"和"典型".然而,仔细观察,很明显,在每个循环中,临时持续时间对象被创建并销毁一次.
// Loop A.
for (;;)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// Do something.
}
Run Code Online (Sandbox Code Playgroud)
现在,如果在循环外创建持续时间对象(作为常量对象),则它将仅针对所有循环构造一次.请参阅下面的代码.
// Loop B.
const auto t = std::chrono::milliseconds(10);
for (;;)
{
std::this_thread::sleep_for(t);
// Do something.
}
Run Code Online (Sandbox Code Playgroud)
问题:由于std :: this_thread :: sleep_for使用"const&"作为其参数类型,所以任何C++编译器都会将Loop A中的临时持续时间对象优化为Loop B吗?
我在下面尝试了一个简单的测试程序 结果表明VC++ 2013没有优化"const&"临时对象.
#include <iostream>
#include <thread>
using namespace std;
class A {
public:
A() { cout << "Ctor.\n"; }
void ReadOnly() const {} // Read-only method.
};
static void Foo(const A & a)
{
a.ReadOnly();
}
int main()
{ …Run Code Online (Sandbox Code Playgroud)