小编XYZ*_*123的帖子

std :: transform可以替换为std :: accumulate吗?

我有一个一般性的问题。我们可以永远替换std::transformstd::accumulate吗?我已经在很多情况/示例中看到了这种替换。因此从理论上讲这是可能的,如果是,那么为什么std::transform要引入?

c++ functional-programming stl std

7
推荐指数
1
解决办法
97
查看次数

为什么 std::make_unique 调用复制构造函数

我想知道为什么 make_unique 调用复制构造函数但不调用默认构造函数。

Node()
{
    std::cout << "default";
}

~Node(){
    std::cout << " Delete";
}

Node(const Node& other ){
    std::cout << "copy";
}

int main(){
    Node<int,int,int,int> test1; //Calling default Cons
    std::unique_ptr<Node<int,int,int,int>> test2  = 
                               std::make_unique<Node<int,int,int,int>>(test1);//Nothing called

    Node<int,int,int,int> *test3 = test2.get();
    Node<int,int,int,int> test4 = Node<int,int,int,int>(*test3);// Calling copy Cons

    std::unique_ptr<Node<int,int,int,int>> test5 = 
                            std::make_unique<Node<int,int,int,int>(test4);//Calling copy Cons
}
Run Code Online (Sandbox Code Playgroud)

例如,在上面显示的代码中:首先,我们创建 Node 对象 -> 调用默认构造函数。然后我们将这个对象包装成智能指针对象 -> 不调用。

但是如果我们对 Node 对象进行深度复制 -> 调用复制构造函数,然后将复制包装到智能指针对象 -> 调用复制构造函数。

它以某种方式与新控制块的创建有关?

c++ smart-pointers deep-copy unique-ptr

4
推荐指数
1
解决办法
6584
查看次数

std :: is_sorted的怪异行为

我正在学习c ++中的断言,并且遇到了std :: is_sorted的怪异行为。

给定一个比较器(c)和std :: strings的未排序向量(v)。我使用std :: sort(v.begin(),v.end(),comparator)。然后使用相同的参数调用std :: is_sorted。结果是错误的,为什么呢?

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <cassert>
int main(){
    auto comparator([](std::string a , std::string b) {return a.length() - b.length();} );
    std::vector<std::string> v {"y" , "yyyy" , "yy" ,
                                 "yy" , "yyyyyyy" , "yyy"};
    assert(false == std::is_sorted(v.begin() , v.end(),comparator));
    std::sort(v.begin(), v.end(),comparator);
    assert(true == std::is_sorted(v.begin() , v.end(),comparator));
}
Run Code Online (Sandbox Code Playgroud)

c++ sorting algorithm assert compare

2
推荐指数
1
解决办法
122
查看次数

使用读取 [ebp+4] 的 MSVC 内联汇编移植到 64 位

我正在使用 Microsoft Visual Studio 2010,并且我正在尝试支持我的项目的 64 位构建。据我所知,64 位架构不支持 __asm 关键字。

以下是当项目仅支持 32 位构建时它的工作原理。

void* 
Class1::Class2::operator new(size_t size) 
{ 
void *pCaller;
__asm mov edx, [ebp+4] 
__asm mov pCaller, edx 
char *pMem = (char *) malloc (sizeof(Class2) + size);
doSomething(pMem, pCaller);
void *ptr = (void *) (pMem + sizeof(Class2)); 
return(ptr);
}
Run Code Online (Sandbox Code Playgroud)

我可以使用预处理器指令使上述函数取决于建筑类型。

void* 
Class1::Class2::operator new(size_t size) 
{
#ifndef _WIN64  
void *pCaller;
__asm mov edx, [ebp+4] 
__asm mov pCaller, edx 
char *pMem = (char *) malloc (sizeof(Class2) + size);
doSomething(pMem, pCaller);
void *ptr …
Run Code Online (Sandbox Code Playgroud)

c++ porting x86-64 inline-assembly visual-c++

1
推荐指数
1
解决办法
892
查看次数