小编Gar*_*and的帖子

C++ 17 std :: filesystem :: path中的本机路径分隔符错误?

从升级当我遇到一个问题#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)

c++ c++17 std-filesystem

18
推荐指数
3
解决办法
2046
查看次数

移动常量对象而不编译警告

我使用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::movestd::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)

c++ c++11 c++17

14
推荐指数
2
解决办法
840
查看次数

在循环中用作"const&"函数参数的临时对象的编译器优化?

我有一个永远的线程循环调用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)

c++ optimization visual-c++ c++11

3
推荐指数
1
解决办法
733
查看次数

标签 统计

c++ ×3

c++11 ×2

c++17 ×2

optimization ×1

std-filesystem ×1

visual-c++ ×1