-5

How to create a temporary value-initialized T* in standard C++?

void foo( int );
void bar( int * );

int main()
{
    foo( int() );  // works. a temporary int - value initialized.
    bar( ??? );    // how to create a temporary int *?
}

Just out of curiousity.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • 3
    I think it's designed so that you can't create a temporary pointer, because doing such a thing doesn't make much sense. What would it point to? If nothing, juts use `nullptr` – BWG Jan 29 '15 at 01:38
  • Does `bar()` dereference the pointer, or is it "safe" to pass a pointer value that is illegal (i.e. points to unallocated memory)? – Jens Jan 29 '15 at 01:55
  • what's the purpose of that? just wondering. – Marson Mao Jan 29 '15 at 02:47
  • @MarsonMao As I wrote: "Just out of curiousity." ... and because I were at a very uncreative state at the time asking that question and couldn't come up with an answer myself. – Swordfish Oct 14 '18 at 16:43
  • @Swordfish nice to know it ;) and it's really an old comment! – Marson Mao Oct 16 '18 at 03:05
  • @MarsonMao I'm intrigued to delete the question, though, since it STILL attracts downvoters for no appearant reason :/ – Swordfish Oct 16 '18 at 03:07
  • @Swordfish i see...lol but fortunately it has only 4 down-votes :p – Marson Mao Oct 16 '18 at 06:45
  • @MarsonMao 2 up, 6 (!) down ... grrr. – Swordfish Oct 16 '18 at 13:57
  • @Swordfish dont worry, u got other good answers to compensate this one. just leave it as a history of ... life :p – Marson Mao Oct 17 '18 at 02:17

3 Answers3

4

The easiest is to use curly braces:

 bar({});

Or a using statement:

using p = int*;
bar( p() );    // how to create a temporary int *?

sehe just reminded me of the stupidly obvious answer of nullptr, 0, and NULL.

bar(nullptr);

And I'm sure there's many more ways.

GCC lets you use compound literals, but technically this isn't allowed

 bar((int*){});

http://coliru.stacked-crooked.com/a/7a65dcb135a87ada

Community
  • 1
  • 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
0

Just for kicks, you can try a typedef:

#include <iostream>
void foo( int ) {}
typedef int* PtrInt;
void bar( PtrInt p ) 
{
   std::cout << "The value of p is " << p;
}

int main()
{
    foo( int() );  
    bar( PtrInt() );  
}

Live Example: http://ideone.com/sjOMlj

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
0

Why not simply use something like this:

int i=0;
bar(&i);  // safe to dereference in bar()

Or are you looking for an inliner? If so, you can use some frown-worthy casting, but then bar() shouldn't actually dereference that pointer:

bar((int*)0); // or use nullptr if your C++ compiler is more recent
Jens
  • 8,423
  • 9
  • 58
  • 78