首页 \ 问答 \ 在容器中使用placement new(Using placement new in a container)

在容器中使用placement new(Using placement new in a container)

我刚刚在C ++中遇到了一些容器实现。 该类使用内部缓冲区来管理其对象。 这是一个没有安全检查简化版本

template <typename E> class Container
{
public:
   Container() : buffer(new E[100]), size(0) {}
   ~Container() { delete [] buffer; }

   void Add() { buffer[size] = E(); size++; }
   void Remove() { size--; buffer[size].~E(); }

private:
   E* buffer;
   int size;
};

如果没有自定义new / delete ,AFAIK将在Container()~Container()冗余地构造/销毁E对象。 这似乎很危险。

Add()使用placement new是防止危险的冗余构造函数/析构函数调用的最佳方法(除了将类绑定到功能齐全的池之外)?

使用placement newnew char[sizeof(E)*100]是否是分配缓冲区的正确方法?


I just came across some container implementation in C++. That class uses an internal buffer to manage its objects. This is a simplified version without safety checks:

template <typename E> class Container
{
public:
   Container() : buffer(new E[100]), size(0) {}
   ~Container() { delete [] buffer; }

   void Add() { buffer[size] = E(); size++; }
   void Remove() { size--; buffer[size].~E(); }

private:
   E* buffer;
   int size;
};

AFAIK this will construct/destruct E objects redundantly in Container() and ~Container() if new/delete are not customized. This seems dangerous.

Is using placement new in Add() the best way to prevent dangerous redundant constructor / destructor calls (apart from binding the class to a fully featured pool)?

When using placement new, would new char[sizeof(E)*100] be the correct way for allocating the buffer?


原文:https://stackoverflow.com/questions/35129485
更新时间:2022-02-26 06:02

最满意答案

get返回一个Observableretry做法是订阅底层的Observable并捕获onError调用,然后重新订阅Observable同时从下游隐藏onError ,从而防止流终止。 只有Observable要求是它必须“从订阅开始”语义或换句话说是一个冷Observable

所以get可以实现为:

function get() {
  var count = 0;
  return Rx.Observable.create(function(observer) {
    if (++count < 2) observer.onError(new Error());
    else {
      observer.onNext("Yay!");
      observer.onCompleted();
    }
  });
}

编辑

我重新阅读了你的问题,并认为我误解了你的要求。 我给出的第一个例子只是一个快速的方法,看看如何制作一个可以retry的普通Observable 。 在给出get的场景中,它正在做某种http请求。

以下是使用RxJS-DOM库来执行Ajax请求,但您也可以使用其他具有Promises库。

//With RxJS DOM
function get(url) {
  return Rx.DOM.ajax({url : url});
} 

//With JQuery Promises
function get(url) {
  return Rx.Observable.defer(function() {
    return $.ajax(url);
  });
}

在这两种情况下,您都会遇到一些可能出错的远程服务器资源。 在它之后添加retry将确保问题不是暂时的网络问题。


get returns an Observable. What retry does is it subscribes to the underlying Observable and captures an onError call and then resubscribes to the Observable while hiding the onError from downstream thus keeping the stream from terminating. Only requirement for the Observable is that it must "start on subscribe" semantics or in other words is a cold Observable.

So get could be implemented as:

function get() {
  var count = 0;
  return Rx.Observable.create(function(observer) {
    if (++count < 2) observer.onError(new Error());
    else {
      observer.onNext("Yay!");
      observer.onCompleted();
    }
  });
}

Edit

I re-read your question and think I misunderstood what you were asking. The first example I gave is just a quick way of seeing how to make a trivial Observable that will work with retry. In the scenario that is given of get it is doing some sort of http request.

The following is using the RxJS-DOM Library to do the Ajax request but you could use other libraries that have Promises as well.

//With RxJS DOM
function get(url) {
  return Rx.DOM.ajax({url : url});
} 

//With JQuery Promises
function get(url) {
  return Rx.Observable.defer(function() {
    return $.ajax(url);
  });
}

In both cases you are hitting some remote server resource which could potentially error. Adding a retry after it would make sure that the issue is not a transient network issue.

相关问答

更多
  • 语法是语法。 它描述了构建正确句子的方式。 例如, 这种水是三角形的在语法上是正确的。 语义与意义有关。 这个水是三角形并不意味着什么,虽然语法是确定的。 谈到语义网最近已经变得新潮。 这个想法是通过附加数据来增强标记(HTML结构),这样计算机可以更容易地理解网页。 Syntax is the grammar. It describes the way to construct a correct sentence. For example, this water is triangular is syn ...
  • 我发现使用示例代码了解移动语义最简单。 我们从一个非常简单的字符串类开始,它只保存一个指向堆分配的内存块的指针: #include #include class string { char* data; public: string(const char* p) { size_t size = strlen(p) + 1; data = new char[size]; memcpy(da ...
  • 在您选择延迟后重试不会那么复杂。 例如,以下( 经过测试的工作代码 )样本在指数延迟(1s,4s,9s,16s,25s ......)后重试: // source observable simply throws error, which is ideal for testing retry concept const source = throwError(new Error('Oops..!')); const smartSource = source.pipe(retryWhen(error => ...
  • 你不能严格地“重试”一个AsyncTask的实例。 您必须创建一个新实例并执行它,就像您完成第一个实例一样。 你不应该遇到递归问题。 You cannot strictly "retry" an instance of AsyncTask. You have to create a new instance and execute it, just as you did the first one. You should not encounter a recursion problem.
  • Spring Retry不是你想要的。 这就是幂等操作,你只需再试一次。 这是OAuth令牌吗? 然后你想要Spring Security OAuth 。 即使不是你想做Oauth2RestTemplate所做的事情:将令牌处理挂钩到客户端。 Spring Retry is not what you want. That is for idempotent operations where you literally just try again. Is this an OAuth token? Then ...
  • 您可以使用np.errstate上下文管理器来捕获警告,就好像它是一个异常: while True: try: print("Before mcmc") with np.errstate(all='raise'): sampler.run_mcmc(pos, 500) print("After mcmc") break except Exception: print("Warning de ...
  • 扩大我的评论: Will Resume会帮助我强迫演员继续前进吗? ...通过Resume,我的意思是重试引发异常的调用。 我怀疑akka Resume意味着保持actor实例,但不重试失败的调用 不,我不相信。 在消息处理失败后, Resume指令将使actor保持活跃状态。 然而,重试消息的一种方法是实际上只使用Restart并利用Actor的preRestart钩子: override def preRestart(t: Throwable, msgBeforeFailure: Option[Any] ...
  • get返回一个Observable 。 retry做法是订阅底层的Observable并捕获onError调用,然后重新订阅Observable同时从下游隐藏onError ,从而防止流终止。 只有Observable要求是它必须“从订阅开始”语义或换句话说是一个冷Observable 。 所以get可以实现为: function get() { var count = 0; return Rx.Observable.create(function(observer) { if (++cou ...
  • Stormpath API尚未提供此功能,因此必须由Web应用程序管理。 但是,Stormpath API可以帮助您,因为您可以将状态存储在帐户的自定义数据对象中,以便您可以跟踪对该特定帐户的尝试次数。 我希望这个答案有所帮助! The Stormpath API does not yet provide this as a feature, so this is something that would have to be managed by your web application. However ...
  • 有几点需要注意。 retry()运算符只是重新订阅其源代码,因此如果您不想再次启动整个迭代,则可以将异步函数合并/连接到链中。 Rx.Observable.from(arr) .concatMap(val => { let attempts = 0; return Rx.Observable.of(val) .delay(500) .concatMap(val => randomFunc(val) .catch((err, caught) => ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。