Since C++11 I have been using the ternary operator to move or throw based on some condition, but with latest GCC (9.1 and trunk) is not working anymore.
I have reduced the problem to this example (Wandbox permalink):
#include <iostream>
#include <memory>
int main()
{
auto p = std::make_unique<int>();
std::cout << "p.get(): " << p.get() << std::endl;
{
std::cout << "Move p into q" << std::endl;
auto q = p ? std::move(p) : throw std::invalid_argument{"null ptr"};
std::cout << …Run Code Online (Sandbox Code Playgroud) 我无法理解何时以及如何在C++ 11中使用新的统一初始化语法.
例如,我得到这个:
std::string a{"hello world"}; // OK
std::string b{a}; // NOT OK
Run Code Online (Sandbox Code Playgroud)
为什么在第二种情况下不起作用?错误是:
error: no matching function for call to ‘std::basic_string<char>::basic_string(<brace enclosed initializer list>)’
Run Code Online (Sandbox Code Playgroud)
使用此版本的g ++ g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2.
对于原始数据,我应该使用什么语法?
int i = 5;
int i{5};
int i = {5};
Run Code Online (Sandbox Code Playgroud) 我已经开始将用FORTRAN编写的高能物理算法迁移到C++中面向对象的方法.FORTRAN代码在很多函数中使用了很多全局变量.
我已将全局变量简化为一组输入变量和一组不变量(变量在算法开始时计算一次,然后由所有函数使用).
此外,我将完整算法分为三个逻辑步骤,由三个不同的类表示.所以,以一种非常简单的方式,我有这样的事情:
double calculateFactor(double x, double y, double z)
{
InvariantsTypeA invA();
InvariantsTypeB invB();
// they need x, y and z
invA.CalculateValues();
invB.CalculateValues();
Step1 s1();
Step2 s2();
Step3 s3();
// they need x, y, z, invA and invB
return s1.Eval() + s2.Eval() + s3.Eval();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
InvariantsTypeX和StepX对象都需要输入参数(这些不仅仅是三个).s1,s2并且s3需要的数据invA和invB对象.s1有一个需要theta的类的成员对象,并且要构造).ThetaMatrixxzinvB是否有一个好的模式来共享输入参数和不变量到用于计算结果的所有对象? …
这个代码,其中有一个const A& a成员B,其中A有一个已删除的拷贝构造函数,不能在GCC 4.8.1中编译,但它在clang 3.4中工作正常:
class A {
public:
A() = default;
A(const A&) = delete;
A& operator=(const A&) = delete;
};
class B{
public:
B(const A& a)
: a{a}
{ }
private:
const A& a;
};
int main()
{
A a{};
B b{a};
}
Run Code Online (Sandbox Code Playgroud)
哪一个编译器是对的?
GCC中的错误是:
prog.cpp: In constructor ‘B::B(const A&)’:
prog.cpp:11:14: error: use of deleted function ‘A::A(const A&)’
: a{a}
^
prog.cpp:4:5: error: declared here
A(const A&) = delete;
^
Run Code Online (Sandbox Code Playgroud)
Ideone:http …