我想知道是否synchronized异常安全?比如,在synchronized块中发生未捕获的异常,是否会释放锁定?
在下面的代码中,作者指出new operator函数调用可能会导致异常,因此此实现不是异常安全的,因为对象状态已在第一行中更改。
String &String::operator =( const char *str ) {
// state is changed
delete [] s_;
if( !str ) str = "";
// exception might occur because of new operator
s_ = strcpy( new char[ strlen(str)+1 ], str );
return *this;
}
Run Code Online (Sandbox Code Playgroud)
在阅读时,我想知道 C 库函数会在 C++ 中抛出异常吗?我知道 C 中没有例外,但由于我们使用的是 C++ 编译器,因此可能会有例外。
那么,我们可以将 C 标准库函数视为异常安全的函数调用吗?
谢谢你。
顺便说一句,为了记录,实现上述功能的正确方法(异常安全)如下。
String &String::operator =( const char *str ) {
if( !str ) str = "";
char *tmp = strcpy( new char[ strlen(str)+1 …Run Code Online (Sandbox Code Playgroud) c++ exception exception-safe exception-safety c-standard-library
如果 Rust 程序发生恐慌,并且假设没有恐慌捕捉器(有一段时间没有),那么不运行析构函数并让操作系统在该过程后进行清理肯定是安全且良好的。Rust 为什么要展开线程?
我能想到的唯一原因是当没有操作系统来回收内存时,但除了这个利基之外,它似乎没有必要。
我了解到线程之间通信的一种方法是共享一些原子数据结构。例如:
struct Point {
int const x, y;
};
std::atomic<Point> some_point_in_shared_memory{Point{0, 0}};
Run Code Online (Sandbox Code Playgroud)
尽管Point::operator=(Point const &)被删除,但调用赋值运算符似乎没有问题std::atomic<Point>,如下所示:
some_point_in_shared_memory = Point{1, 2};
Run Code Online (Sandbox Code Playgroud)
如何实施此操作?
我可能会想到的一种解决方案是使用placement new在旧对象之上构造一个新对象,但显然它不是异常安全的。还是因为Point可以简单地复制而没关系?
如何确保某个类的某个实例永远不会为null?有人告诉我使用Debug.Assert(),但这样做,我只会确保代码在调试模式下工作,而我想确保在发布中的is-never-null条件.
例如,在过去我编写的代码如下:
public string MyString
{
get
{
if(instance1.property1.Equals("bla"))
{
return bla;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果instance1为null,则抛出异常.我想避免犯这样的错误并在将来产生这样的例外.
谢谢,
请参阅下面的具体示例,说明问题:
我有一种方法,可以根据服务器的响应对用户进行身份验证.方法是这样的:
/// <summary>
/// attempts authentication for current user
/// </summary>
/// <returns></returns>
public AuthResult CheckUser()
{
WebRequest request = WebRequest.Create(GetServerURI);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postdata = "data=" + HttpUtility.UrlEncode(SerializeAuth());
byte[] arr = Utils.AppDefaultEncoding.GetBytes(postdata);
request.ContentLength = arr.Length;
request.Timeout = Convert.ToInt32(TimeUtils.GetMiliseconds(10, TimeUtils.TimeSelect.Seconds));
Stream strToWrite = request.GetRequestStream();
strToWrite.Write(arr, 0, arr.Length);
WebResponse response = request.GetResponse();
using (Stream dataFromResponse = response.GetResponseStream())
{
using …Run Code Online (Sandbox Code Playgroud) c++ ×2
exception ×2
c# ×1
coding-style ×1
destructor ×1
java ×1
rust ×1
stdatomic ×1
synchronized ×1