经常提到-std标志应该用于指定编译C++程序时希望使用的标准(例如,-std=c++11或-std=gnu++11).一个通常没有解决的相关问题(至少据我所知;例如,参见Dennis根据Oskar N选择的答案高度评价的评论)是如何确定默认的C++标准是什么正在被编译器使用.
我相信可以通过查看手册页(至少对于g ++)来判断,但我想问这是否正确以及是否有更明确/具体的方法:
在描述中-std,手册页列出了所有C++标准,包括GNU方言.在一个特定的标准下,它是相当不明确的,This is the default for C++ code.(C标准有一个类似的陈述:) This is the default for C code..
例如,对于g++/gcc version 5.4.0,这列在下面gnu++98/gnu++03,而对于g++/gcc version 6.4.0,它列在下面gnu++14.
这自然似乎表明了默认标准,但它写得如此不显眼,以至于我并不完全确定.如果是这种情况,也许这对那些对这个同样的问题感到疑惑的人有用.其他C++编译器还有其他方便的方法吗?
编辑:我遇到了这个相关的问题,但那里的答案相当复杂,并没有产生具体的,明确的陈述.也许我应该在得到证实之后将其作为对这个问题的答案.
下面的最小工作示例在使用选项 1 或选项 2下的代码时编译,但在使用选项 3 下的代码时不编译。我假设emplace_back()隐式使用/调用move构造函数,那么为什么需要显式move()?跟r-valuevs. 有关系l-value吗?或者这是否与std::unique_ptr需要转让所有权有关?(我对这些概念还是陌生的,尤其是在这种情况下。)
为了完整push_back()起见,除非move()调用,否则选项 4 with也不会编译。
#include <iostream>
#include <vector>
#include <memory>
class Beta {
public:
Beta(int x, int y, int z): mX(x), mY(y), mZ(z) { };
int mX; int mY; int mZ;
};
class Alpha {
public:
std::vector<std::unique_ptr<Beta>> betaVec;
void addBeta(int x, int y, int z) {
// only choose one of the following options:
// option …Run Code Online (Sandbox Code Playgroud) 在编写需要多个独立的随机数分布/序列(下面的示例中有两个)的代码时,似乎有两种典型的方法来实现(伪)随机数生成。一种是简单地使用一个random_device对象为两个独立引擎生成两个随机种子:
std::random_device rd;
std::mt19937 en(rd());
std::mt19937 en2(rd());
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};
Run Code Online (Sandbox Code Playgroud)
另一个涉及使用random_device对象来创建seed_seq使用多个随机“源”的对象:
// NOTE: keeping this here for history, but a (hopefully) corrected version of
// this implementation is posted below the edit
std::random_device rd;
std::seed_seq seedseq{rd(), rd(), rd()}; // is there an optimal number of rd() to use?
std::vector<uint32_t> seeds(5);
seedseq.generate(seeds.begin(), seeds.end());
std::mt19937 en3(seeds[0]);
std::mt19937 en4(seeds[1]);
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};
Run Code Online (Sandbox Code Playgroud)
在这两个中,是否有首选方法?为什么?如果是后者,random_device在生成seed_seq对象时是否有最佳数量的“源” ?
是否有比我上面概述的这两个实现中的任何一个更好的随机数生成方法?
谢谢!
(希望)修正seed_seq多个发行版的实现版本:
std::random_device …Run Code Online (Sandbox Code Playgroud)