在以下示例中:
void bad_function()
{
char_t * ptr = 0;
// MISRA doesn't complains here, it allows cast of char* to void* pointer
void* p2 = ptr;
// the following 2 MISRA violations are reported in each of the casts bellow (two per code line)
// (1) Event misra_violation: [Required] MISRA C++-2008 Rule 5-2-7 violation: An object with pointer type shall not be converted to an unrelated pointer type, either directly or indirectly
// (1) Event misra_violation: [Required] MISRA C++-2008 Rule …Run Code Online (Sandbox Code Playgroud) 我想要有接受枚举默认参数的函数。
但我无法在 PyBind11枚举示例和文档中找到提供枚举默认值的正确方法,例如:
struct Pet
{
enum Kind
{
Dog = 0,
Cat
};
Pet(const std::string &name) : name(name)
{
}
void setName(const std::string &name_)
{
name = name_;
}
const std::string &getName() const
{
return name;
}
Kind test(Kind kind = Dog)
{
if(kind == Dog)
std::cout << "Dog" << std::endl;
if(kind == Cat)
std::cout << "Cat" << std::endl;
return kind;
}
std::string name;
};
PYBIND11_MODULE(pet,m)
{
py::class_<Pet> pet(m, "Pet");
pet.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName)
.def("test", …Run Code Online (Sandbox Code Playgroud) 我想学习在 VS2012 中使用 C++ 11 std::threads,我写了一个非常简单的 C++ 控制台程序,它有两个线程,它只是增加一个计数器。我还想测试使用两个线程时的性能差异。测试程序如下:
#include <iostream>
#include <thread>
#include <conio.h>
#include <atomic>
std::atomic<long long> sum(0);
//long long sum;
using namespace std;
const int RANGE = 100000000;
void test_without_threds()
{
sum = 0;
for(unsigned int j = 0; j < 2; j++)
for(unsigned int k = 0; k < RANGE; k++)
sum ++ ;
}
void call_from_thread(int tid)
{
for(unsigned int k = 0; k < RANGE; k++)
sum ++ ;
}
void test_with_2_threds()
{
std::thread t[2]; …Run Code Online (Sandbox Code Playgroud) 我喜欢了解赞成与反对者拥有和不拥有这样的演员。在包括Stack Overflow在内的多个地方,我可以看到const char*强制转换被认为是一个坏主意,但我不确定为什么吗?
编写通用例程和模板时,缺少(const char*)和强制始终使用强制转换c_str()会产生一些问题。
void CheckStr(const char* s)
{
}
int main()
{
std::string s = "Hello World!";
// all below will not compile with
// Error: No suitable conversion function from "std::string" to "const char *" exists!
//CheckStr(s);
//CheckStr((const char*)s);
// strlen(s);
// the only way that works
CheckStr(s.c_str());
size_t n = strlen(s.c_str());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我有大量接受const char*输入的文本处理功能,并且我希望std::string每次使用都能够使用c_str()。但是以这种方式std::string,const char*如果没有额外的努力,模板函数就不能同时使用。
作为一个问题,我可以看到一些运算符重载问题,但可以解决这些问题。
例如,正如[eerorika]指出的那样,通过允许隐式强制转换为指针,我们允许将非自愿的字符串类包含在布尔表达式中。但是我们可以通过删除bool运算符轻松解决此问题。更进一步,强制转换操作符必须明确:
class …Run Code Online (Sandbox Code Playgroud)