例如,使用元组:
#include <tuple> // std::tuple, std::make_tuple, std::tie
int num;
char letter;
std::tuple<int,char> num_letter;
num_letter = std::make_tuple(10, 'a');
std::tie(num, letter) = num_letter; // unpack num_letter into num and letter
Run Code Online (Sandbox Code Playgroud)
有没有相当于对的东西?
// ...
num_letter = std::make_pair(10, 'a');
std::pair_tie(num, letter) = num_letter;
Run Code Online (Sandbox Code Playgroud) 两者之间是否存在功能差异:
void foo(const Bar& bar) {
Bar bar_copy(bar);
// Do stuff with bar_copy
}
Run Code Online (Sandbox Code Playgroud)
和
void foo(Bar bar) {
// Do stuff with bar
}
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,为什么多个声明(和一个定义)适用于全局变量x,而不适用y于main()函数内部的局部变量?它显示以下2个错误:
1)没有联系的'y'重新声明
2)之前的'y'声明就在这里
为什么它显示局部变量但不是全局变量的错误?不仅是我的书,而且本论坛的以下2个链接清楚地表明我们可以多次声明一个变量(尽管只定义一次).
并且请注意解释第一个错误"没有链接"的部分是什么,"没有连接的'y'的重新声明"是什么意思?什么联系和谁?将局部变量链接到哪里?
#include<stdio.h>
int x;
int x;
int x=303;
int main(void)
{
int y;
int y;
int y=776; //Works fine if above 2 declarations are removed!!
printf("The value of x is %d,and of y is %d",x,y);
}
Run Code Online (Sandbox Code Playgroud) 这是一个准确的描述吗?是否有意义?
您是否确保在unique_ptr超出范围之前不会删除它指向的对象[即使您没有使用unique_ptr]?
我有同样的问题,发现这里的蟒蛇,但红宝石.
我需要输出一个这样的小数:0.00001,而不是1e-5.
有关我的特定问题的更多信息,我正在使用输出到文件 f.write("My number: " + small_number.to_s + "\n")
对于我的问题,准确性并不是一个大问题,所以只需要做一个if语句来检查small_number <1e-5然后打印0是否正常,它看起来并不像它应该的那样优雅.
那么更普遍的方法是什么呢?
我很确定这是有效的.
int foo = 51;
int* bar = &foo;
foo = 3;
Run Code Online (Sandbox Code Playgroud)
所以酒吧仍然有效,并且*bar == 3.
如果我们说,怎么样?
std::unique_ptr<int> foo(new int(51)); // should probably use make_unique
int* bar = foo.get();
foo.reset(new int(3));
Run Code Online (Sandbox Code Playgroud)
我有保证*bar == 3吗?或者我通过继续引用bar导致未定义的行为?
我有一个函数,以下列方式生成枚举器:
def create_example_enumerator(starting_value)
current = starting_value
e = Enumerator.new do |y|
loop do
current += 1
y << current
end
end
end
Run Code Online (Sandbox Code Playgroud)
目前的行为非常简单.
> e = create_example_enumerator(0)
#<Enumerator: details>
> e.next
1
> e.next
2
> e.rewind
#<Enumerator: details>
> e.next
3
Run Code Online (Sandbox Code Playgroud)
我想将e.rewind枚举器重置为它的起始值.有没有一种很好的方法可以在使用无限枚举器的同时做到这一点?
有一些宏可以防止类被复制,例如: 宏禁止类复制和赋值.谷歌-vs- Qt
仅仅通过在我班级中使用unique_ptr,我会获得相同的结果吗?如果是这样,有没有理由不这样做?例如
class Foo {
private:
std::unique_ptr<int> DISABLE_COPY;
};
Run Code Online (Sandbox Code Playgroud) 我使用的常见模式是:
const string& GetConstString() {
static const auto* my_string = new string("useful const string");
return *my_string;
}
Run Code Online (Sandbox Code Playgroud)
[这不是泄漏!观看此视频]
这解决了许多终身问题.string可以用任何具有重要dtor的类型替换.
如果你的类型有默认的ctor和普通的dtor,你可以这样做
const MyType& GetConstMyType() {
static MyType my_type;
return my_type;
}
Run Code Online (Sandbox Code Playgroud)
我正在和一个有默认ctor和普通dtor的班级一起工作.我想知道这个类是默认值还是值初始化.事实证明,它对于类类型并不重要.所以这成了一个学术问题[例如,如果你有这个类的数组].
但它是默认值还是值初始化?