例如:如果我使用引用矢量元素的变量,则矢量的功能发生了变化,则我的引用将变为无效引用。
#include <vector>
#include <iostream>
std::vector<int> v = {1, 2, 3};
int main() {
int &r = v[0];
std::cout << r << std::endl;
v.reserve(256);
std::cout << r << std::endl;
std::cout << v[0] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以避免这种情况吗?或者只是不引用向量元素?
现在,我需要检测是否将我的类创建为stack / global / thread_local变量,例如:
class Foo {
public:
Foo() {
if(im_on_stack) {
std::cout << "I'm on stack" << std::endl;
} else if(im_in_global) {
std::cout << "I'm in global" << std::endl;
} else if(im_a_thread_local) {
std::cout << "I'm a thread_local" << std::endl;
} else {
std::cout << "I'm on ohters location" << std::endl;
}
}
};
class Bar {
Foo mFoo;
};
Foo gFoo;
thread_local Foo tFoo;
int main() {
Foo lFoo;
}
Run Code Online (Sandbox Code Playgroud)
并且输出应该是:
I'm on ohters location
I'm in …Run Code Online (Sandbox Code Playgroud) 如果我的udp包大于mtu会怎么样?假设我的包是512字节,封装后,包是572字节.在传输中,一些中间节点将其大小固定为512字节,那么会发生什么?我的包裹是否被丢弃了?
一般来说,适合大多数网络情况的udp包的最佳尺寸是多少?
首先,让我使这个问题更具体。
通过说
检查类型的析构函数是否可以被“忽略”
我意思是
检查类在实例消失时是否没有副作用。
我在做什么:
我正在为我们的C ++项目编写垃圾收集库,我需要提高性能。如果我可以检测到传入类型T在销毁时没有副作用,那么我可以检查所有活动对象,其余所有都是垃圾,可以标记为“垃圾”(典型的年轻一代收集技术)。但是,如果它有副作用,我必须扫描每个濒死的对象并运行它的析构函数。
例如:
struct S1 {
int i;
}; // can be ignored
struct S2 {
int i;
~S2() {
}
}; // can be ignored
struct S3 {
S3() {
std::cout << "S3()" << std::endl;
}
virtual ~S3() {
std::cout << "~S3()" << std::endl;
}
}; // can not be ignored, destructor has side effect
struct S4 {
S3 s3;
}; // can not be ignored, destructor has side effect(calling s3's …Run Code Online (Sandbox Code Playgroud) 这是我的测试代码:
void Test::test(const std::vector<uint8_t>& buffer) {
std::vector<uint8_t> data;
data = std::move(buffer);
}
Run Code Online (Sandbox Code Playgroud)
这段代码似乎毫无意义,这只是一个例子.我在我的ide中使用代码导航来找出=运算符的实现,我发现当前处理的是一个operator=(const vector<_Tp, _Alloc>& __x),它正在执行复制作业.
我搜索了整个文件,没有任何功能operator=(vector<_Tp, _Alloc>&& __x),所以我如何从移动和rvalue featrue中受益?
我的c ++标题在/usr/include/c++/5,我检查的文件是vector.tcc.
我想将两个局部变量放入一对并返回,这是我的代码:
#include <utility>
class Foo {
};
class Bar {
};
std::pair<Foo, Bar> test() {
Foo foo;
Bar bar;
return std::make_pair<Foo, Bar>(foo, bar);
}
Run Code Online (Sandbox Code Playgroud)
我得到了
Run Code Online (Sandbox Code Playgroud)main.cpp:92:10: error: no matching function for call to 'make_pair' /usr/bin/../lib/gcc/x86_64-linux-gnu/7.4.0/../../../../include/c++/7.4.0/bits/stl_pair.h:524:5: note: candidate function not viable: no known conversion from 'Foo' to 'Foo &&' for 1st argument make_pair(_T1&& __x, _T2&& __y)
如果我使用return std::make_pair<Foo, Bar>(std::move(foo), std::move(bar));,编译将成功。那我想念什么?