std::unique_ptr::operator-> 有签名
pointer operator->() const noexcept;
Run Code Online (Sandbox Code Playgroud)
所以operator->是常量而是返回一个可变的指针.这允许代码如:
void myConstMemberFunction() const
{
myUniquePtrMember->nonConstFunction();
}
Run Code Online (Sandbox Code Playgroud)
为什么标准允许这样做,以及防止使用的最佳方法是什么?
这个问题需要很长的设置,但请忍受。
考虑以下文件:
Type1.hpp
#ifndef TYPE1_HPP
#define TYPE1_HPP
struct Type1
{
int a;
int b;
};
#endif
Run Code Online (Sandbox Code Playgroud)
Type2.hpp
#ifndef TYPE2_HPP
#define TYPE2_HPP
struct Type2
{
int c;
int d;
};
#endif
Run Code Online (Sandbox Code Playgroud)
MyTemplate.hpp
#ifndef MYTEMPLATE_HPP
#define MYTEMPLATE_HPP
template <typename T>
struct MyTemplate
{
T t;
};
#endif
Run Code Online (Sandbox Code Playgroud)
Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTIONS_HPP
struct Type1;
struct Type2;
template <typename T> struct MyTemplate;
int func(const MyTemplate<Type1>& param);
int func(const MyTemplate<Type2>& param);
#endif
Run Code Online (Sandbox Code Playgroud)
Functions.cpp
#include "Functions.hpp"
#include "MyTemplate.hpp"
#include "Type1.hpp"
#include "Type2.hpp"
int func(const MyTemplate<Type1>& …Run Code Online (Sandbox Code Playgroud) 我读过你不应该相信枚举的底层实现,无论是签名还是未签名。由此我得出结论,您应该始终将枚举值转换为要与之进行比较的类型。像这样:
enum MyEnum { MY_ENUM_VALUE = 0 };
int i = 1;
if (i > static_cast<int>(MY_ENUM_VALUE))
{
// do stuff
}
unsigned int u = 2;
if (u > static_cast<unsigned int>(MY_ENUM_VALUE))
{
// do more stuff
}
Run Code Online (Sandbox Code Playgroud)
这是最佳做法吗?
编辑:如果枚举是匿名的,情况会改变吗?
考虑这个示例程序:
#include <iostream>
typedef enum { A, B, C } MyEnum;
struct S
{
S(int) { std::cout << "int" << std::endl; }
S(MyEnum) { std::cout << "MyEnum" << std::endl; }
};
S f()
{
return A;
}
int main()
{
S const s = f();
}
Run Code Online (Sandbox Code Playgroud)
使用 clang 和 gcc 编译,生成一个可执行文件,在运行时打印“MyEnum”。C++ 标准保证这种行为吗?
以下代码是否会导致数据争用:
int f()
{
int i = 0;
std::thread t{[&]{ i = 1; }};
t.join();
return i;
}
Run Code Online (Sandbox Code Playgroud)
没有互斥或原子用于i访问。
std :: thread :: join的文档讨论了“线程的完成与join()的相应成功返回的同步”,但是我不确定在这种情况下是否有意义。