Roosembert Palacios
Roosembert Palacios

Reputation: 41

Initializate a pointer to struct in C++

Okay, so, I'm trying to do something like a "Compound Literal" AFAIK, I remember doing this on C while programming for embedded devices, but I'd to move to C++. I know that C++ is not C, I thought they were compatible.

GaussBlurParams *GBPs= &(GaussBlurParams) {Size(5,5), (int)3, (int)3, (int)0};

But compiler complains with: taking address of temporary [-fpermissive] error. I though on using a 'new' constructor but It gets worse.

Here's my Definition of GaussBlurParams

typedef struct gaussBlurParams{
    cv::Size ksize;
    int stdX;
    int stdY;
    int borderType;
} GaussBlurParams;

How can I overcome this problem?

Best Regards!

EDIT: Okay, This is what I'm doing:

void ProcessFrames(Mat In, Mat Out, GaussBlurParams GBPs){
    GaussianBlur(In, Out, GBPs.ksize, GBPs.stdX, GBPs.stdY);
}

createTrackbar("Kernel Size Height", "Output Stream Viewer", &GBPs->ksize.height, 10, NULL);
createTrackbar("Kernel Size Width", "Output Stream Viewer", &GBPs->ksize.width, 10, NULL);
createTrackbar("STD X Sigma", "Output Stream Viewer", &GBPs->stdX, 10, NULL);
createTrackbar("STD Y Sigma", "Output Stream Viewer", &GBPs->stdX, 10, NULL);
ProcessFrames(*Frame, *OutputFrame, *GBPs);

EDIT: Here's my Code on Github if you want to take a look! (Commit)

Upvotes: 0

Views: 102

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

Firstly, there are no compound literals in C++.

Secondly, compound literal declared in local scope creates an automatic object, which gets automatically destroyed once the containing block ends. Are you sure you need a pointer to such a short-lived object? (I'm not saying that this is necessarily wrong, but it might easily be.)

Anyway, in C++ you are not allowed to create pointers to temporary objects. (At least not the way you do it - with the built-in unary & operator.) Just declare a named object and make your pointer point to that named object. Forget about temporaries and compound literals.

GaussBlurParams GBP = { cv::Size(5,5), 3, 3, 0 };
GaussBlurParams *GBPs = &GBP;

Again, make sure the lifetime of that named object is as long as the lifetime of the pointer value, or you will end up with invalid dangling pointer.

Upvotes: 1

Related Questions