通过按位运算确定返回类型(Determining return type via bitwise operation)

我在java文档中游荡,突然发现这段代码:

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor)
{
    Objects.requireNonNull(keyExtractor);
    return (Comparator<T> & Serializable)
        (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

谁能解释一下返回声明后会发生什么样的魔法? 好的,该方法的结果由lambda表达式与功能界面结合确定。 但那之前写的是什么? 它是通过按位运算转换返回类型吗? 我不明白。 据我所知,bitwise仅适用于数字。 我在哪里可以更具体地阅读这个案例?


I was wandering throught java docs and suddenly found this code:

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor)
{
    Objects.requireNonNull(keyExtractor);
    return (Comparator<T> & Serializable)
        (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

Can anyone explain what kind of magic is going on after the return statement? Okay, the result of the method is determined by lambda expression in combination with functional interface. But what is it written before that? Is it casting return type via bitwise operation? I don't get it. As far I know bitwise is applicable only with numbers. Where can I read about this case more specifically?


原文:https://stackoverflow.com/questions/30061674
2023-08-03 18:08

满意答案

你的析构函数肯定是错的。 类的析构函数不会也不能delete该对象的内存。

如果没有虚函数,你对公共继承的反对意见是什么? (至少)有两种方法可以防止某人通过基指针意外删除派生对象。 一个是protected基础析构函数。

另一种方法是将派生类的动态分配实例直接填充到shared_ptr 。 这甚至可以是shared_ptr<Base>

std::shared_ptr<Base> foo(new DerivedA(...));

由于shared_ptr具有捕获其参数类型的模板构造函数,因此Base*指针将在与shared_ptr关联的删除函数中转换为DerivedA* ,因此会被正确删除。 没有人会如此愚蠢地尝试从shared_ptr提取指针并将其删除为Base*

当然,如果你没有虚函数,那么当衍生类之间的唯一区别就是它们在构造函数中设置的时候,这个技巧才真正有用。 否则,您最终需要从shared_ptr向下转换Base*指针,在这种情况下,您应该首先使用shared_ptr<DerivedA>


Your destructor is definitely wrong. The destructor of a class does not and must not delete the memory for the object.

What's your objection to public inheritance without virtual functions? There are (at least) a couple of ways to prevent someone accidentally deleting a derived object through a base pointer. One is to make the base destructor protected.

Another is to stuff dynamically-allocated instances of the derived class straight into a shared_ptr. This can even be a shared_ptr<Base>:

std::shared_ptr<Base> foo(new DerivedA(...));

Because shared_ptr has a template constructor that captures the type of its argument, the Base* pointer will be converted to DerivedA* in the deleter function associated with the shared_ptr, and hence deleted correctly. Nobody should ever be so daft as to try to extract a pointer out of a shared_ptr and delete it as Base*.

Of course if you have no virtual functions, then the trick is only really useful when the only difference between the derived classes is what they set up in their constructors. Otherwise you'll end up needing to downcast the Base* pointer from the shared_ptr, in which case you should have used a shared_ptr<DerivedA> to begin with.

相关问答

更多

C ++析构函数返回(C++ destructor with return)

不,你不能通过return语句来防止对象被破坏,这只是意味着在这个时候,dtor的身体的执行就会结束。 之后,还会被毁坏(包括其成员和基地),记忆仍将被释放。 你迁移异常。 Class2::~Class2() noexcept(false) { if (status != FINISHED) throw some_exception(); } Class1::~Class1() { myClass2->status = FINISHED; try { de...

C ++:CRTP析构函数?(C++ : CRTP destructor?)

你的析构函数肯定是错的。 类的析构函数不会也不能delete该对象的内存。 如果没有虚函数,你对公共继承的反对意见是什么? (至少)有两种方法可以防止某人通过基指针意外删除派生对象。 一个是protected基础析构函数。 另一种方法是将派生类的动态分配实例直接填充到shared_ptr 。 这甚至可以是shared_ptr<Base> : std::shared_ptr<Base> foo(new DerivedA(...)); 由于shared_ptr具有捕获其参数类型的模板构造函数,因此B...

这个C ++析构函数是多余的吗?(Is this C++ destructor redundant?)

是的,析构函数是完全冗余的。 如你所说,代码中还有其他警告标志。 例如,使用typedef struct在C ++中没有任何意义,它与空的析构函数一样多余:代码是由C ++编写的边际掌握,一定会有更多的错误(一方面,类名无效)由于全球范围的领先优势)。 Yes, the destructor is completely redundant. As you’ve said yourself the code has other warnings signs. Using typedef struct...

CRTP(C ++)的各种错误(Various errors with CRTP (C++))

你需要实现你的专业功能: template<> const string& Entity<Client>::name() const { return _name; } template<> Client& Entity<Client>::name(const string& name) { _name = name; return *This(); } 并且还添加公共继承: class Client : public Entity<Client> 所以你可以访问na...

C ++析构函数示例(C++ destructor example)

对于ListElement,使值为0,链接为0(NULL)。 您不需要重置析构函数中的任何值,因为在执行析构函数后,值不会存在。 您需要确定的主要事情是使用delete堆上分配的所有元素(即使用new )(或者在数组的情况下delete [] )。 对于LinkedList,遍历元素并为所有元素调用ListElementDestructor。 对于在堆栈上分配的对象,当对象超出范围时,将自动调用该对象。 对于动态分配的对象(即使用new创建),在使用delete析构函数时会调用析构函数。 换句话说...

C ++需要析构函数(C++ need for destructor function)

这是成员自己不负责的额外清理。 或者在资源管理的情况下确保与他对象相关的资源被正确释放。 请记住并非所有成员都会调用析构函数(指针没有析构函数)。 所以如果你有指针,你需要手动管理它们。 带指针的示例资源管理。 shared_ptr::~shared_ptr() { if (decrementReferenceCountAndCheckForZero()) { cleanupResources(); } } 例。 使用框架。 没有一个成员知道框架,但工作人...

C ++中的析构函数(destructor in C++)

您遇到错误和无关的警告。 这个错误是因为你为析构函数使用了一个初始化器,这是没有意义的,也不是有效的语法。 你要: ~AB() { } // destructor 警告是因为你没有声明你的析构函数是虚拟的。 具有虚拟方法的类应该具有虚拟析构函数 : virtual ~AB() { } You're getting an error and an unrelated warning. The error is because you're using an initializer for you...

需要C ++ / CLI完成析构函数(The need for C++/CLI finalize destructor)

出于同样的原因,你在C#中有一个Dispose方法和一个Finalizer。 粗略地说,在C ++ / CLI中,析构函数对应于Dispose,Finalilzer对应于终结器。 我粗略地说,因为C ++ / CLI为您实现了Dispose模式 。 也就是说,如果调用delete(即调用析构函数),它将确保终结器被抑制。 如果未调用delete,则终结器将在GC时运行。 就像在C#中一样 在析构函数中,您可以清理托管对象和非托管对象。 在终结器中,您只能清理非托管对象,因为此时(当垃圾收集器正在运...

析构函数是正常的函数调用吗?(Is destructor a normal function call?)

如果要显式调用析构函数,则必须从与被调用的析构函数相同类型的对象中调用它。 否则,这将产生未定义的行为: 在显式析构函数调用中,析构函数名称显示为〜后跟类型名称或decltypespecifier,表示析构函数的类类型。 析构函数的调用遵循成员函数的通常规则(9.3); 也就是说,如果对象不是析构函数的类类型而不是从析构函数的类类型派生的类(包括通过空指针值调用析构函数),则程序具有未定义的行为。 另请注意,如果显式调用析构函数,则在实例所在的作用域的末尾,只要对象已在堆栈上实例化,析构函数将被隐...

C ++ CRTP类层次结构(C++ CRTP class hierarchy)

使用CRTP支持更深层次的继承层次结构通常是通过在继承层次结构中在您自己的类之间“插入”CRTP类来实现的: struct empty {}; template <class Derived, class Base = empty> struct crtp_services : Base {}; class base : public crtp_services<base> {}; class derived : public crtp_services<derived, base> {}...

相关文章

更多

ServletOutputStream cannot be resolved to a type

在使用jsp生成web图片时遇到这个问题,这是源代码中的一条语句,源代码可以执行,可是一将源码放入ec ...

Tomcat源码里,return (factory)有特殊作用么

/** * Return the SAXParserFactory we will use, ...

深入浅出dwr系列教程之2传参数及处理各种类型的返回值

深入浅出dwr系列教程之2传参数及处理各种类型的返回值

The content of element type "package" must match "...

在编写后台登陆模块时,将许多默认的设置放在一个名为default的package 里。然后再定义其他 ...

用axis开发java web service中关于服务返回复杂类型的问题

我是个初学者。我做了一个简单的例子,遇到点问题,希望大家可以帮忙看看 首先这里是个pojo类,名字为 ...

微信公众号接口添加菜单时错误(errcode":40017 invalid button type)

POST提交时总是报错: {&quot;errcode&quot;:40017,&quot;errms ...

Java运算符

Java运算符 计算机的最基本用途之一就是执行数学运算,作为一门计算机语言,Java也提供了一套 ...

关于两种对象类型使用

直接描述的我的问题了。 我的需求是读取本地或异地的数据,程序中用到ResultSet(本地读取)和D ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本