相关疑难解决方法(0)

为什么不使用#define隐藏在这里工作的unique_ptr丑陋?

隐藏unique_ptr丑陋的以下"技巧"有什么问题?

class Drawable;
typedef unique_ptr<Drawable> pDrawable;
#define newDrawable(...) pDrawable(new Drawable (##__VA_ARGS__))
Run Code Online (Sandbox Code Playgroud)

前两个很好.但第三个是在VS2012中导致错误:

 23 IntelliSense: "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx>::
_Myt &) [with _Ty=Drawable, _Dx=std::default_delete<Drawable>]" (declared at line 1447 of
"C:\vs2012\VC\include\memory") is inaccessible  file.h  36  26  
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这不会起作用,除非我误解了C++如何定义宏的工作原理.我以为它只会替换这段代码:

newDrawable(a, b, c)
Run Code Online (Sandbox Code Playgroud)

unique_ptr<Drawable>(new Drawable(a, b, c));
Run Code Online (Sandbox Code Playgroud)

我知道unique_ptr无法复制,但我不是在复制它.我呢?

编辑:

我收到了一些关于"使用"宏的请求:

如果我用它,它会被使用如下:

pDrawable myDraw = newDrawable();
Run Code Online (Sandbox Code Playgroud)

我想翻译成:

unique_ptr<Drawable> myDraw = unique_ptr<Drawable>(new Drawable());
Run Code Online (Sandbox Code Playgroud)

但是,如果没有visual studio给出以下错误,我甚至无法编译宏.就好像#define中的某些内容本身是不允许的.在我进行定义的行上返回错误,而不是在我调用define的地方.

请参阅此处了解make_unique无效的原因:make_unique无法编译

EDIT2

我已经回答了下面的问题.上面的代码确实可以编译和工作.

c++ visual-c++ c++11 visual-studio-2012

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

更改std :: unique_ptr的删除

我想改变default_deleterstd::unique_ptr.这很容易实现,但有一个不方便 - 我必须使用2个模板参数而不是一个来声明变量,如下所示:

std::unique_ptr<MyType, MyDeleter<MyType>> myVar;
Run Code Online (Sandbox Code Playgroud)

正如你可能看到声明很长,我有一种感觉,我可以使用更短的版本,但我不知道如何:)

是否有可能宣布某种与MyUniquePtr<T>此相同的东西std::unique_ptr<T, MyDeleter<T>>

编辑:Matthieu M.已经回答,但不幸的是我无法在Visual Studio中使用此功能,因为它没有实现.还有其他方法可以有这种行为吗?

c++ c++11

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

为什么我不能将unique_ptr与fread一起使用?

如果你运行下面的代码fread将返回0.如果你p改为使用buf而不是unique_ptr它将工作.为什么?我在MSVC 2013中运行了这个

#include <iostream>
#include <map>
#include <memory>
using namespace std;

int main(int argc, char *argv[]) {
    char buf[1024 * 32];
    auto buf2 = make_unique<char>(1024 * 32);

    {
        memset(buf, 0, sizeof buf);
        FILE *f = fopen("tmpfile", "wb");
        printf("write = %d\n", fwrite(buf, 1, sizeof buf, f));
        fclose(f);
    }

    //char*p = 0 ? buf2.get() : buf;
    //char*p = buf;
    char*p = buf2.get();

    FILE *f = fopen("tmpfile", "r+b");

    printf("read = %d\n", fread(p, 1, sizeof buf, …
Run Code Online (Sandbox Code Playgroud)

c++ unique-ptr c++14

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

无法初始化512x512阵列

嘿所有我想只是为什么我在尝试初始化512x512阵列时不断出现堆栈溢出错误?有人可以帮忙吗?下面是我的代码的一部分

CImg<float> image("lena8bit.jpg"); 
CImgDisplay main_disp(image,"Main image");

    int ImgArray [512][512];
Run Code Online (Sandbox Code Playgroud)

基本上我想做的就是从图像中获取像素值并将其存储到此数组中.图像为512x512,因此是阵列大小.

希望听到你的回答,谢谢!

c++ arrays

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

标签 统计

c++ ×4

c++11 ×2

arrays ×1

c++14 ×1

unique-ptr ×1

visual-c++ ×1

visual-studio-2012 ×1