我正在迭代一个向量,需要迭代器当前指向的索引.AFAIK这可以通过两种方式完成:
it - vec.begin()std::distance(vec.begin(), it)这些方法的优点和缺点是什么?
如果我有一个带有虚拟析构函数的基类.有一个派生类来声明一个虚拟析构函数吗?
class base {
public:
virtual ~base () {}
};
class derived : base {
public:
virtual ~derived () {} // 1)
~derived () {} // 2)
};
Run Code Online (Sandbox Code Playgroud)
具体问题:
我已经多次听过和读过,最好将异常作为引用而不是引用来引用.为什么是
try {
// stuff
} catch (const std::exception& e) {
// stuff
}
Run Code Online (Sandbox Code Playgroud)
比...更好
try {
// stuff
} catch (std::exception& e) {
// stuff
}
Run Code Online (Sandbox Code Playgroud) 默认情况下,从getter函数返回副本(1)或引用(2)会更好吗?
class foo {
public:
std::string str () { // (1)
return str_;
}
const std::string& str () { // (2)
return str_;
}
private:
std::string str_;
};
Run Code Online (Sandbox Code Playgroud)
我知道2)可能更快,但不必因(N)RVO.1)关于悬挂引用更安全,但对象可能会过时或永远不会存储引用.
当你写一个课程时,你的默认值是什么,而且还不知道(但)性能和生命周期问题是否重要?
附加问题:当成员不是普通字符串而是向量时,游戏会改变吗?
两者之间有什么区别吗?
std::string s1("foo");
Run Code Online (Sandbox Code Playgroud)
和
std::string s2 = "foo";
Run Code Online (Sandbox Code Playgroud)
?
基本上我使用以下代码来设置串口的波特率:
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
tcsetattr(fd, TCSANOW, &options);
Run Code Online (Sandbox Code Playgroud)
这非常有效.但是我知道我必须使用波特率为307200的设备进行通信.我该如何设置?cfsetispeed(&options, B307200);不起作用,没有B307200定义.
我尝试使用MOXA Uport 1150(实际上是USB转串口转换器)和英特尔主板的标准串口.我不知道后者的确切类型,setserial只是将其报告为16550A.
我有一个类和一个具有相同名称的枚举值.在课堂内我想使用枚举,这会产生错误.有没有办法在不重命名或移动到不同的命名空间的情况下使用枚举?
例:
namespace foo {
enum bar {
BAD
};
class BAD {
void worse () {
bar b = BAD; // error
}
};
};
Run Code Online (Sandbox Code Playgroud) 我有一个可以从多个线程访问的类.getter和setter函数都有锁.是否需要用于吸气功能的锁?为什么?
class foo {
public:
void setCount (int count) {
boost::lock_guard<boost::mutex> lg(mutex_);
count_ = count;
}
int count () {
boost::lock_guard<boost::mutex> lg(mutex_); // mutex needed?
return count_;
}
private:
boost::mutex mutex_;
int count_;
};
Run Code Online (Sandbox Code Playgroud) 是否可以为枚举定义多个输出运算符?我想用这个
std::ostream& operator<< (std::ostream& os, my_enum e);
Run Code Online (Sandbox Code Playgroud)
操作员 (1) 打印人类可读的文本并 (2) 将其转换为一些代码以存储在数据库中。
谢谢
c++ ×9
const ×2
enums ×2
baud-rate ×1
c ×1
class ×1
coding-style ×1
exception ×1
inheritance ×1
iterator ×1
linux ×1
locking ×1
mutex ×1
operators ×1
return-value ×1
serial-port ×1
string ×1