我正在学习c++并尝试一些东西。编译器没有在注释2行抛出错误。
int main(){
vector<double> a1;
a1.push_back(3);
a1.push_back(7);
a1.push_back(2);
vector<double>& a2 = a1; //COMMENT 1: This line has no error
vector<double>& a4 = print(a2); //COMMENT 2: Why this line has error?
最近,我被告知在C++中找到一个临时变量,将其提升到具有完整的词法范围:
class Foo {
public:
Foo() {
std::cout << "A";
}
~Foo() {
std::cout << "B";
}
};
int main(void)
{
// Prints "ACB", showing the temporary being promoted to having lexical scope.
const Foo&
在引用中存储对象的返回值是否有效?
class A { ... };
A myFunction()
{
A myObject;
return myObject;
} //myObject goes out of scope here
void mySecondFunction()
{
A& mySecondObject = myFunction();
}
为了避免将myObject复制到mySecondObject,是否可以这样做?不再需要myObject,它应该与mySecondObject完全相同,所以从理论上讲,将对象的所有权从一个对象传递到另一个对象会
可能重复:
#include <string>
void foo1(const std::string& s = std::string());
void foo2(std::string& s = std::string());
void foo3(const std::string s = std::string());
void foo4(std::string s = std::string());
error at foo2(): default argument for ‘std::string& s’ has type ‘st
这个问题回答了为什么在下面的例子中的参考捕获不是绝对必要的。但另一方面,如果捕获了错误,则会得到一个错误。
错误似乎是由foo()的递归性质触发的。
template<typename T>
constexpr int bar(const T& x) { // NOK
//constexpr int bar(T x) { // OK
return x;
}
template<typename T>
int foo(const T& l) {
constexpr auto x = l() - 1;
auto y = [&]
假设我有一个A类,它的构造函数需要一个参数x。
class A
{
public:
int a;
A(int x) { a = x; std::cout << a << std::endl; }
~A() {}
};
现在我想分配一个A的数组,并将它包装在另一个B类中(实际上它应该是一个A的二维数组,映射到一个一维数组,这就是我需要包装它的原因)。因为A的构造函数需要参数,所以我不能使用新的,所以我必须有一个A**。我也不想让B知道x,所以我的B是这样的:
class B
{
private:
A** As;
const int
我有一个"sum“类,它包含两个对现有int的引用(比方说)。我想创建一个"copy“方法来深度复制整型数。我以为我永远不需要在代码中手动delete对象,这要归功于智能指针,但在这个解决方案中我必须这样做。此外,对于如此琐碎的任务(我需要在几个类中重复),它太复杂了。有没有更直接的解决方案?
注意:我不想为每个对象添加一个布尔成员(标志)来决定是否必须删除it(在我的例子中,这并不比析构函数中的std::set检查开销更好)
#include <set>
struct sum {
const int &a, &b;
static st
有人能解释一下为什么这段代码不会产生编译器错误吗?
class Foo
{
public:
int _x;
};
Foo getFoo()
{
Foo myfoo;
myfoo._x = 10;
return myfoo;
}
int _tmain()
{
// shouldn't this line of code be a compiler error?
Foo& badfoo = getFoo();
return 0;
}
在最新的C++标准中,它意味着:
for (foo : bar)
baz;
等同于:
{
auto && r = bar;
for ( auto it = r.begin(), end = r.end(); it != end; ++it )
{
foo = *it;
baz;
}
}
当上面的bar是一个返回集合的函数调用时,例如:
vector<string> boo();
即
for (auto bo : boo())
...
这行代码不是变成了:
auto&& r
最近,我感到惊讶的是,下面的代码也是用clang、gcc和msvc编译的(至少现在的版本是这样的)。
struct A {
static const int value = 42;
};
constexpr int f(A a) { return a.value; }
void g() {
A a; // Intentionally non-constexpr.
constexpr int kInt = f(a);
}
我的理解是,对f的调用不是i,因为i不是,但我似乎错了。这是一个正确的标准支持的代码还是某种编译器扩展?
我有一些代码看起来像这样
struct A
{
int i;
A(int i) : i(i) {}
~A()
{
cout << "destroy " << i << endl;
}
};
using p = shared_ptr<A>;
p f(int i)
{
return make_shared<A>(i);
}
int main()
{
auto i = f(1);
cout << "a" <<